package com.baoteng.rbspy.service.impl;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.mustache.MustacheResourceTemplateLoader;
import org.springframework.stereotype.Service;

import com.baoteng.rbspy.cache.LocalCacheManager;
import com.baoteng.rbspy.config.car.RbSysConfig;
import com.baoteng.rbspy.config.car.URLConfig;
import com.baoteng.rbspy.exception.BizException;
import com.baoteng.rbspy.exception.SystemException;
import com.baoteng.rbspy.exception.VehicleCodeException;
import com.baoteng.rbspy.model.Model;
import com.baoteng.rbspy.model.agree.AgreePO;
import com.baoteng.rbspy.model.kind.BIPO;
import com.baoteng.rbspy.model.kind.CIPO;
import com.baoteng.rbspy.model.kind.KindConfig;
import com.baoteng.rbspy.model.kind.KindPO;
import com.baoteng.rbspy.model.kind.ShipTaxPO;
import com.baoteng.rbspy.model.kind.TaxQueryPO;
import com.baoteng.rbspy.model.privy.PersonAddress;
import com.baoteng.rbspy.model.privy.PersonContact;
import com.baoteng.rbspy.model.privy.PrivyItemPO;
import com.baoteng.rbspy.model.privy.PrivyPO;
import com.baoteng.rbspy.model.privy.group.GoupItemPO;
import com.baoteng.rbspy.model.privy.group.GroupTax;
import com.baoteng.rbspy.model.quote.MainQuote;
import com.baoteng.rbspy.model.quote.OtherQuote;
import com.baoteng.rbspy.model.quote.RandomProposal;
import com.baoteng.rbspy.model.quote.Seller;
import com.baoteng.rbspy.model.quote.SummaryProposal;
import com.baoteng.rbspy.model.quote.VehicleQuote;
import com.baoteng.rbspy.model.renewal.RenewalPO;
import com.baoteng.rbspy.model.request.GroupEditRequest;
import com.baoteng.rbspy.model.request.PrivyEditRequest;
import com.baoteng.rbspy.model.request.PrivyRequest;
import com.baoteng.rbspy.model.request.RenewalRequest;
import com.baoteng.rbspy.model.request.TaxRequest;
import com.baoteng.rbspy.model.request.VehicleModelRequest;
import com.baoteng.rbspy.model.request.proposal.StageProposal;
import com.baoteng.rbspy.model.response.ResponseModel;
import com.baoteng.rbspy.model.response.assist.AnciIndiConfQueryVo;
import com.baoteng.rbspy.model.response.assist.AssistResponse;
import com.baoteng.rbspy.model.response.assist.Commissions;
import com.baoteng.rbspy.model.response.quote.BiInsuredemandVO;
import com.baoteng.rbspy.model.response.quote.CiInsureAnnualTaxes;
import com.baoteng.rbspy.model.response.quote.CiInsureDemand;
import com.baoteng.rbspy.model.response.quote.CiInsureDemandCheckVo;
import com.baoteng.rbspy.model.response.quote.CiInsureDemandPayList;
import com.baoteng.rbspy.model.response.quote.CiInsureDemandRepets;
import com.baoteng.rbspy.model.response.quote.CiInsureDerateTaxes;
import com.baoteng.rbspy.model.response.quote.CiInsureTax;
import com.baoteng.rbspy.model.response.quote.CiInsureVO;
import com.baoteng.rbspy.model.response.quote.ErrorMessageVo;
import com.baoteng.rbspy.model.response.quote.PayDetailQuote;
import com.baoteng.rbspy.model.response.quote.PrpCfixations;
import com.baoteng.rbspy.model.response.quote.PrpCitemCarExt;
import com.baoteng.rbspy.model.response.quote.PrpCitemKinds;
import com.baoteng.rbspy.model.response.quote.PrpCprofitDetails;
import com.baoteng.rbspy.model.response.quote.QuoteResponse;
import com.baoteng.rbspy.model.vehicle.VehicleModelPO;
import com.baoteng.rbspy.mq.MessageHandler;
import com.baoteng.rbspy.service.CaptchaService;
import com.baoteng.rbspy.service.KindService;
import com.baoteng.rbspy.service.OkHttpClientService;
import com.baoteng.rbspy.service.PrivyService;
import com.baoteng.rbspy.service.QuoteService;
import com.baoteng.rbspy.service.RenewalService;
import com.baoteng.rbspy.service.VehicleService;
import com.baoteng.rbspy.util.BaseUtil;
import com.baoteng.rbspy.util.BeanConvertUtil;
import com.baoteng.rbspy.util.DateUtils;
import com.baoteng.rbspy.util.JsonUtils;
import com.baoteng.rbspy.vo.CaptchaVO;
import com.baoteng.rbspy.vo.request.ApplyInsureRequest;
import com.baoteng.rbspy.vo.request.InvoiceInfo;
import com.baoteng.rbspy.vo.request.Quote;
import com.baoteng.rbspy.vo.request.UserInfo;
import com.baoteng.rbspy.vo.request.UserVehicleInfo;
import com.baoteng.rbspy.vo.request.VehicleInfo;
import com.baoteng.rbspy.vo.response.ApplyQuoteResponse;
import com.baoteng.rbspy.vo.response.ClaimPayInfo;
import com.baoteng.rbspy.vo.response.PromotionPO;
import com.baoteng.rbspy.vo.response.QuoteResult;
import com.fasterxml.jackson.core.type.TypeReference;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.samskivert.mustache.Mustache;

import net.sf.cglib.beans.BeanCopier;

@Service
public class QuoteServiceImpl implements QuoteService {

	private final Logger LOGGER = LoggerFactory.getLogger(QuoteServiceImpl.class);

	@Autowired
	OkHttpClientService okHttpClientService;

	@Autowired
	OkHttpClientService noRedirectHttpClient;

	@Autowired
	private Mustache.Compiler compiler;

	@Autowired
	MustacheResourceTemplateLoader mustacheTemplateLoader;

	@Autowired
	URLConfig urlConfig;

	@Autowired
	RbSysConfig rbSysConfig;

	BeanConvertUtil beanUtil = BeanConvertUtil.newInstance();

	@Autowired
	RenewalService renewalService;

	@Autowired
	VehicleService vehicleService;

	@Autowired
	PrivyService privyService;

	@Autowired
	KindService kindService;

	@Autowired
	CaptchaService picsCaptchaService;
	
	@Autowired
	MessageHandler messageHandler;

	@Autowired
	LocalCacheManager cache;
	
	private String getRandomProposalNo(String type) {
		ResponseModel<RandomProposal> randomResponse = okHttpClientService
				.getHtml(urlConfig.getQuotePreUrl() + "?bizType=PROPOSAL&editType=NEW", RandomProposal.class);
		return randomResponse != null && randomResponse.isSuccessful() && randomResponse.getBody() != null
				? randomResponse.getBody().getRandomProposalNo()
				: null;
	}

	public ApplyQuoteResponse saveQuote(String quoteNum) throws Exception {
		
		ApplyQuoteResponse quote = cache.getQuote(quoteNum).orElse(null);
		
		if(quote!=null && (StringUtils.isNotBlank(quote.getBiNo()) || StringUtils.isNotBlank(quote.getCiNo()))){
			return quote;
		}
		
		StageProposal stage = cache.getProposal(quoteNum).orElse(null);
		if(stage==null) throw new BizException("报价已失效，请重新报价。");
		ApplyQuoteResponse _quoteResponse = stage.getQuoteResponse();
		if(_quoteResponse==null ) throw new BizException("报价已失效，请重新报价。");
		String strVehicle = stage.getStrVehicle();
		String strPrivy = stage.getStrPrivy();
		String strAgree = stage.getStrAgree();
//		List<AgreePO> agressList = stage.getAgrees();
		
//		String strAgree = compiler.compile(mustacheTemplateLoader.getTemplate("quote_agree")).execute(new Object() {
//			@SuppressWarnings("unused")
//			List<AgreePO> agrees = agressList;
//		});
		String strBi = compiler.compile(mustacheTemplateLoader.getTemplate("quote_bi")).execute(stage.getBi());
		String strCi = compiler.compile(mustacheTemplateLoader.getTemplate("quote_ci")).execute(stage.getCi());
		String strTax = compiler.compile(mustacheTemplateLoader.getTemplate("quote_tax")).execute(stage.getCi().getTax()!=null?stage.getCi().getTax():new ShipTaxPO());
		String strMain = compiler.compile(mustacheTemplateLoader.getTemplate("quote_main")).execute(stage.getMain());
		// strOther =
		// compiler.compile(mustacheTemplateLoader.getTemplate("quote_other")).execute(ci.getTax1());
		// other.setBiCheckAnswer(biCheckAnswer);
		String strCheck = compiler.compile(mustacheTemplateLoader.getTemplate("quote_check")).execute(new OtherQuote());
		StringBuilder templateBuilder = new StringBuilder();
		// 辅助核保
		AssistResponse assists = assistCheck(templateBuilder.append(strMain).append(strVehicle).append(strPrivy).append(strBi)
				.append(strCi).append(strTax).append(strAgree).append(stage.getStrOther()).append(strCheck).toString());
		
		SummaryProposal summary = stage.getSummary();
		if (assists.getOperCommRateCIUp() != null && assists.getSumPremiumCI() != null) {
			assists.setOperCommRateCIUpAmount(
					BaseUtil.getMoneyNumber(assists.getSumPremiumCI() * assists.getOperCommRateCIUp() / 100));
		}
		if (assists.getOperCommRateBIUp() != null && assists.getSumPremiumBI() != null) {
			assists.setOperCommRateBIUpAmount(
					BaseUtil.getMoneyNumber(assists.getSumPremiumBI() * assists.getOperCommRateBIUp() / 100));
		}
		if (assists.getDiscountRate() != null && assists.getOperSellExpensesRate() != null) {
			assists.setActProfitRate(
					BaseUtil.getMoneyNumber(assists.getDiscountRate() + assists.getOperSellExpensesRate()));
			if (assists.getActProCommRate() != null) {
				assists.setExpProCommRateUp_Disc(
						BaseUtil.getMoneyNumber(assists.getActProfitRate() - assists.getActProCommRate()));
			}
			if (assists.getActProCommRateUp() != null) {
				assists.setActProCommRateUp_Disc(
						BaseUtil.getMoneyNumber(assists.getActProfitRate() - assists.getActProCommRateUp()));
			}
		}
		assists.setExpRiskNote(assists.getStandbyField1());
		assists.setStandbyField1(StringUtils.joinWith(",", assists.getOperCommRateCIUpAmount(),
				assists.getOperCommRateBIUpAmount(), assists.getActProfitRate(), assists.getExpProCommRateUp_Disc(),
				assists.getActProCommRateUp_Disc(), assists.getExpRiskNote(), assists.getStrKindBusiTypeA(),
				assists.getStrKindBusiTypeB(), assists.getStrKindBusiTypeC(), assists.getStrKindBusiTypeD(),
				assists.getStrKindBusiTypeE()));

		String strSummary = compiler.compile(mustacheTemplateLoader.getTemplate("proposal_summary")).execute(summary);
		String strPlan = compiler.compile(mustacheTemplateLoader.getTemplate("quote_cplan")).execute("cplan");
		String strAssists = compiler.compile(mustacheTemplateLoader.getTemplate("proposal_assist")).execute(assists);
		String strOther = compiler.compile(mustacheTemplateLoader.getTemplate("proposal_other")).execute("other");
		// 跟单费用，只实现广东计算方法，其它省份需要增加
		templateBuilder.setLength(0);
		getCseller(templateBuilder.append(strMain).append(stage.getStrVehicle()).append(stage.getStrPrivy()).append(strBi).append(strCi).append(strTax)
				.append(stage.getStrAgree()).append(strSummary).append(strPlan).append(strAssists).append(strOther).toString(),
				summary);
		if (assists != null) {
			if (assists.getAnciIndiConfQueryVoList() == null)
				assists.setAnciIndiConfQueryVoList(Lists.newArrayList());
			assists.getAnciIndiConfQueryVoList().addAll(summary.getVos());
		}
		summary.setSellerMaxFeeGR1(summary.getSellerMaxFeeGR());
		summary.setSellerMaxFeeGS1(summary.getSellerMaxFeeGS());
		summary.setSellerMaxFeeGT1(summary.getSellerMaxFeeGT());
		summary.setSellerMaxFeeGC1(summary.getSellerMaxFeeGC());
		summary.setSellerMaxFeeGB1(summary.getSellerMaxFeeGB());

		strSummary = compiler.compile(mustacheTemplateLoader.getTemplate("proposal_summary")).execute(summary);
		strAssists = compiler.compile(mustacheTemplateLoader.getTemplate("proposal_assist")).execute(assists);
		// 生成模板后再赋值，要不会有问题
		List<Commissions> commissions = Lists.newArrayList();
		if (!Strings.isNullOrEmpty(stage.getMain().getStartDateBI())) {
			Commissions biCommission = new Commissions();
			biCommission.setCostType("01");
			biCommission.setRiskCode("DAA");
			biCommission.setCostRate(0d);
			biCommission.setCoinsRate(100d);
			biCommission.setCostFee(0d);
			biCommission.setCostRateUpper(summary.getSellerMaxFee().toString());
			biCommission.setCurrency("AED");
			biCommission.setAgreementNo("1");
			biCommission.setSumPremium(
					BaseUtil.getMoneyNumber(summary.getSumPremium() - summary.getSumPremium() * 0.06 / 1.06));
			biCommission.setConfigCode("1");
			commissions.add(biCommission);
		}
		if (!Strings.isNullOrEmpty(stage.getMain().getStartDateCI())) {
			Commissions ciCommission = new Commissions();
			ciCommission.setCostType("01");
			ciCommission.setRiskCode("DZA");
			ciCommission.setCostRate(0d);
			ciCommission.setCoinsRate(100d);
			ciCommission.setCostFee(0d);
			ciCommission.setCostRateUpper(summary.getSellerMaxFeeCi().toString());
			ciCommission.setCurrency("AED");
			ciCommission.setAgreementNo("1");
			ciCommission.setSumPremium(BaseUtil.getMoneyNumber(summary.getSumPremiumCI() - summary.getSumPremiumCI() * 0.06 / 1.06));
			ciCommission.setConfigCode("1");
			commissions.add(ciCommission);
		}
		summary.setCommissions(commissions);
		if (!Strings.isNullOrEmpty(stage.getMain().getStartDateBI())) {
			templateBuilder.setLength(0);
			stage.setSummary(summary);
			this.feeBi(templateBuilder.append(strMain).append(strVehicle).append(strPrivy).append(strBi).append(strCi).append(strTax)
					.append(strAgree).append(strSummary).append(strPlan).append(strAssists).append(strOther).toString(),
					stage);
		}

		if (!Strings.isNullOrEmpty(stage.getMain().getStartDateCI())) {
			templateBuilder.setLength(0);
			stage.setSummary(summary);
			strSummary = compiler.compile(mustacheTemplateLoader.getTemplate("proposal_summary")).execute(summary);
			this.feeCi(templateBuilder.append(strMain).append(strVehicle).append(strPrivy).append(strBi).append(strCi).append(strTax)
					.append(strAgree).append(strSummary).append(strPlan).append(strAssists).append(strOther).toString(),
					stage);
		}

		strSummary = compiler.compile(mustacheTemplateLoader.getTemplate("proposal_summary")).execute(summary);
		// 生成投保单
		templateBuilder.setLength(0);
		templateBuilder.append(strMain).append(strVehicle).append(strPrivy).append(strBi).append(strCi).append(strTax)
				.append(strAgree).append(strSummary).append(strPlan).append(strAssists).append(strOther);
		List<PayDetailQuote> plans = refreshPlan(templateBuilder.toString());
		strPlan = compiler.compile(mustacheTemplateLoader.getTemplate("proposal_cplan"))
				.execute(new PlanTemplate(plans));
		templateBuilder.setLength(0);
		templateBuilder.append(strMain).append(strVehicle).append(strPrivy).append(strBi).append(strCi).append(strTax)
				.append(strAgree).append(strSummary).append(strPlan).append(strAssists).append(strOther);
		quote2Proposal(templateBuilder.toString(), _quoteResponse);
		this.cache.putQuote(quoteNum,_quoteResponse);
		return _quoteResponse;
	}

	/**
	 * 险种代码 第二列为条款码 3列为calculateFlag 4列为relateSpecial 机动车交通事故强制责任保险-- 050100 050001
	 * 机动车损失保险 -- 050202 050051 Y11Y000 050930 盗抢 -- 050501 050054 N11Y000 050932
	 * 第三者责任保险 -- 050602 050052 Y21Y000 050931 车上人员责任险（司机） -- 050711 050053 Y21Y00
	 * 050933 车上人员责任险（乘客） -- 050712 050053 Y21Y00 050934 车身划痕损失险 050211 050059
	 * N12Y000 050937 玻璃单独破碎险 050232 050056 N32N000 指定修理厂险 050253 050065 N32N000
	 * 自燃损失险 050311 050057 N12Y000 050935 机动车损失保险无法找到第三方特约险 050451 050064 N32N000
	 * 发动机涉水损失险 050461 050060 N32Y000 050938 不计免赔险（车损险） 050930 050066 N33N000
	 * 不计免赔险（三者险） 050931 050066 N33N000 不计免赔险（车上人员（司机）） 050933 050066 N33N000
	 * 不计免赔险（车上人员（乘客）） 050934 050066 N33N000 不计免赔险（盗抢险） 050932 050066 N33N000
	 * 不计免赔险（车身划痕损失险） 050937 050066 N33N000 不计免赔险（发动机涉水损失险） 050938 050066 N33N000
	 * 不计免赔险（自燃损失险） 050935 050066 N33N000 商业险赋值
	 */
	public void bizKindItemSet(QuoteResult quote, PrpCitemKinds kind,ApplyInsureRequest request) {
		switch (kind.getKindCode()) {
		case "050202":
			quote.setCheSun_amount(kind.getPremium());
			// quote.setDamage(kind.getAmount());
			break;
		case "050501":
			quote.setDaoQiang_amount(kind.getPremium());
			// quote.setRobbery(kind.getAmount());
			break;
		case "050602":
			quote.setSanZhe_amount(kind.getPremium());
			// quote.setRobbery(kind.getAmount());
			break;
		case "050711":
			quote.setSiJi_amount(kind.getPremium());
			// quote.setDriverAmount(kind.getAmount());
			break;
		case "050712":
			quote.setChengKe_amount(kind.getPremium());
			// quote.setPassengerAmount(kind.getAmount());
			break;
		case "050211":
			quote.setHuaHen_amount(kind.getPremium());
			// quote.setScratch(kind.getAmount());
			break;
		case "050232":
			quote.setBoLi_amount(kind.getPremium());
			quote.setGlass(request.getQuote().getGlass());
			// quote.setGlass(kind.getAmount());
			break;
		case "050253":
			quote.setHcXiuLiChang_amount(kind.getPremium());
			// quote.setDesignatedService(kind.getAmount());
			break;
		case "050311":
			quote.setZiRan_amount(kind.getPremium());
			// quote.setFire(kind.getAmount());
			break;
		case "050451":
			quote.setHcSanFangTeYue_amount(kind.getPremium());
			// quote.setHcSanFangTeYue(kind.getAmount());
			break;
		case "050461":
			quote.setSheShui_amount(kind.getPremium());
			// quote.setEngine(kind.getAmount());
			break;
		case "050930":
			quote.setBuJiMianCheSun_amount(kind.getPremium());
			break;
		case "050931":
			quote.setBuJiMianSanZhe_amount(kind.getPremium());
			break;
		case "050933":
			quote.setBuJiMianSiJi_amount(kind.getPremium());
			break;
		case "050934":
			quote.setBuJiMianChengKe_amount(kind.getPremium());
			break;
		case "050932":
			quote.setBuJiMianDaoQiang_amount(kind.getPremium());
			break;
		case "050937":
			quote.setBuJiMianHuaHen_amount(kind.getPremium());
			break;
		case "050938":
			quote.setBuJiMianSheShui_amount(kind.getPremium());
			break;
		case "050935":
			quote.setBuJiMianZiRan_amount(kind.getPremium());
			break;
		}
	}

	public ApplyQuoteResponse quote(ApplyInsureRequest request) throws Exception {
		MainQuote main = mainQuotehandler(request, new MainQuote());
		VehicleQuote vehicle = vehicleQuotehandler(request, new VehicleQuote(),main);
		PrivyPO privy = privyQuotehandler(request, new PrivyPO());
		BIPO bi = biQuotehandler(request, main);
		CIPO ci = ciQuotehandler(request, privy,main);
		
		if(ci.getTax()!=null) {
			if(vehicle.getCarLotEquQuality()!=null) ci.getTax().setCarLotEquQuality(String.format("%.2f", vehicle.getCarLotEquQuality()));
			ci.getTax().setExtendChar2(BaseUtil.matchNumberAndLetters(vehicle.getBrandName()));
		}
		AgreePO agree = new AgreePO();
		agree.setSerialNo(1);
		agree.setClauseCode("996063");
		agree.setClauseName("被保险人联系方式特约");
		agree.setEngageFlag("2");
		agree.setMaxCount("12");
		agree.setBeforeContent("本保单被保险人联系电话");
		 agree.setCenterContent(request.getBeibao()!=null?request.getBeibao().getMobile():request.getOwner().getMobile());
		agree.setAfterContent("，如有错误，请您致电95518更改；请关注“广州人保财险”官方微信号，免费兑换精彩服务。");
		agree.setClauses(agree.getBeforeContent() + request.getBeibao().getMobile() + agree.getAfterContent());
		agree.setIndex(0);
		List<AgreePO> agreeList = Lists.newArrayList(agree);
		//修改专修厂费率，如果是进口车修改为0.15设置prpCitemCar.coefficient3为空，国产为0.1
		if("02".equals(vehicle.getCountryNature())) {
			vehicle.setCoefficient3(null);
		}
		StringBuilder sb = new StringBuilder();
		
		String strMain = compiler.compile(mustacheTemplateLoader.getTemplate("quote_main")).execute(main);
		String strVehicle = compiler.compile(mustacheTemplateLoader.getTemplate("quote_vehicle")).execute(vehicle);
		String strPrivy = compiler.compile(mustacheTemplateLoader.getTemplate("quote_privy")).execute(privy);
		String strBi = compiler.compile(mustacheTemplateLoader.getTemplate("quote_bi")).execute(bi);
		String strCi = compiler.compile(mustacheTemplateLoader.getTemplate("quote_ci")).execute(ci);
		String strTax = compiler.compile(mustacheTemplateLoader.getTemplate("quote_tax"))
				.execute(ci.getTax() != null ? ci.getTax() : new ShipTaxPO());
		String strAgree = compiler.compile(mustacheTemplateLoader.getTemplate("quote_agree")).execute(new Object() {
			@SuppressWarnings("unused")
			List<AgreePO> agrees = agreeList;
		});
		OtherQuote other = new OtherQuote();
		other.setCarChecker(rbSysConfig.getHandler1Code());
		other.setProjectCode(rbSysConfig.getProjectCode());
		other.setProjectName(rbSysConfig.getProjectName());
		other.setOperatorCode(rbSysConfig.getOperatorCode());
		other.setOperatorName(rbSysConfig.getOperatorName());
		other.setArgueSolution(rbSysConfig.getArgueSolution());
		other.setArbitBoardName(rbSysConfig.getArbitBoardName());
		other.setArbitBoardNameDes(rbSysConfig.getArbitBoardNameDes());
		String strOther = compiler.compile(mustacheTemplateLoader.getTemplate("quote_other")).execute(other);
		String strCheck = compiler.compile(mustacheTemplateLoader.getTemplate("quote_check")).execute(other);
		sb.append(strMain).append(strVehicle).append(strPrivy).append(strBi).append(strCi).append(strTax)
				.append(strAgree).append(strOther).append(strCheck);

		ResponseModel<Model<QuoteResponse>> jsonResponse = okHttpClientService.postJson(urlConfig.getQuoteUrl(),
				sb.toString(), new TypeReference<Model<QuoteResponse>>() {
				});
		if (jsonResponse == null || !jsonResponse.isSuccessful() || jsonResponse.getBody() == null) {
			throw new SystemException("系统异常,报价失败");
		}

		if (StringUtils.isNotBlank(jsonResponse.getBody().getMsg())) {
			String[] msgs = jsonResponse.getBody().getMsg().split(",");
			if ("0".equals(msgs[0] )) {
				throw new BizException(msgs[1]);
			} else if ("1".equals(msgs[0] )) {
				throw new VehicleCodeException(jsonResponse.getBody().getMsg());
			} else {
				throw new BizException(jsonResponse.getBody().getMsg());
			}
		}
		QuoteResponse quoteResponse = jsonResponse.getBody().getData().get(0);

		CiInsureDemandCheckVo ciInsureDemandCheckVo = quoteResponse.getBiInsuredemandVoList() != null
				&& !quoteResponse.getBiInsuredemandVoList().isEmpty()
						? quoteResponse.getBiInsuredemandVoList().get(0).getCiInsureDemandCheckVo()
						: null;
		CiInsureDemandCheckVo ciInsureDemandCheckCIVo = quoteResponse.getCiInsureVOList() != null
				&& !quoteResponse.getCiInsureVOList().isEmpty()
						? quoteResponse.getCiInsureVOList().get(0).getCiInsureDemandCheckVo()
						: null;

		if ((ciInsureDemandCheckVo != null && "1".equals(ciInsureDemandCheckVo.getRenewalFlag()))
				|| (ciInsureDemandCheckCIVo != null && "1".equals(ciInsureDemandCheckCIVo.getRenewalFlag()))) {
			String flagCheck = "";
			if (ciInsureDemandCheckVo != null && "1".equals(ciInsureDemandCheckVo.getRenewalFlag())) {
				other.setBiFlag("CHECK");
				other.setBiRiskCode("DAA");
				other.setBiDemandNo(ciInsureDemandCheckVo.getDemandNo());
				flagCheck = flagCheck + "1";
			} else {
				flagCheck = flagCheck + "0";
			}
			if (ciInsureDemandCheckCIVo != null && "1".equals(ciInsureDemandCheckCIVo.getRenewalFlag())) {
				other.setCiFlag("CHECK");
				other.setCiRiskCode("DAZ");
				other.setCiDemandNo(ciInsureDemandCheckCIVo.getDemandNo());
				flagCheck = flagCheck + "1";
			} else {
				flagCheck = flagCheck + "0";
			}
			quoteResponse = picsCheck(ciInsureDemandCheckVo, ciInsureDemandCheckCIVo, other,
					new StringBuilder().append(strMain).append(strVehicle).append(strPrivy).append(strBi).append(strCi)
							.append(strTax).append(strAgree).append(strOther).toString());
			if (quoteResponse == null) {
				throw new BizException("验证码识别错误");
			}
		}

		if (StringUtils.isNotBlank(quoteResponse.getErrMessage())) {
			String errMsg = quoteResponse.getErrMessage();
			if (errMsg.split(",")[0] == "BDJY") {
				throw new BizException(errMsg.split(",")[1]);
			} else if (errMsg.split("^")[0] == "9308" || errMsg.split("^")[0] == "9309") {
				CiInsureDemandRepets repet = quoteResponse.getBiInsuredemandVoList().get(0).getCiInsureDemandRepets()
						.get(0);
				throw new BizException("商业险重复投保！"
						+ (StringUtils.isNotBlank(repet.getInsurerCode()) ? "重复投保保险公司:" + repet.getInsurerCode() : "")
						+ (StringUtils.isNotBlank(repet.getPolicyNo()) ? "重复投保保单号:" + repet.getPolicyNo() : "")
						+ (repet.getStartDate() != null
								? "起保日期:" + BaseUtil.dateTime2String(repet.getStartDate(), "yyyy-MM-dd")
								: "")
						+ (repet.getEndDate() != null
								? "终保日期:" + BaseUtil.dateTime2String(repet.getEndDate(), "yyyy-MM-dd")
								: "")
						+ (repet.getBillDate() != null
								? "签单日期:" + BaseUtil.dateTime2String(repet.getBillDate(), "yyyy-MM-dd")
								: "")
						+ (StringUtils.isNotBlank(repet.getVinNo()) ? "车辆识别代号:" + repet.getVinNo() : "")
						+ (StringUtils.isNotBlank(repet.getEngineNo()) ? "发动机号:" + repet.getEngineNo() : ""));
			} else {
				throw new BizException("定价返回：" + errMsg);
			}
		}
		ApplyQuoteResponse _quoteResponse = new ApplyQuoteResponse();
		_quoteResponse.setCityId(request.getCityId());
		_quoteResponse.setCityName(request.getCityName());
		_quoteResponse.setQuoteResult(new QuoteResult());
		BeanCopier.create(Quote.class, QuoteResult.class, false).copy(request.getQuote(),
				_quoteResponse.getQuoteResult(), null);
		if (StringUtils.isNotBlank(quoteResponse.getClaimsMessage())) {
			_quoteResponse.setOtherMessage(quoteResponse.getClaimsMessage());
		}
		double biSumPremium = 0;
		double biSumamount = 0;
		double ciSumPremium = 0;
		double ciSumamount = 122000;
		double biDiscount = 1;
		double ciDiscount = 1;
		double biSumDiscount = 0;
		double ciSumDiscount = 0;
		double biSumBenchPremium = 0;
		double biSumNetPremium = 0;
		// 处理商业险
		if (quoteResponse.getBiInsuredemandVoList() != null && !quoteResponse.getBiInsuredemandVoList().isEmpty()) {
			BiInsuredemandVO prpmain = quoteResponse.getBiInsuredemandVoList().get(0);
			if (main.getFixations() != null) {
				main.getFixations().addAll(prpmain.getPrpCfixations());
			} else {
				main.setFixations(prpmain.getPrpCfixations());
			}
			if(prpmain.getPrpCprofitFactors()!=null) {
				for(int k=0;k<prpmain.getPrpCprofitFactors().size();k++) {
					prpmain.getPrpCprofitFactors().get(k).setIndex(k);
				}
			}
			bi.setFactors(prpmain.getPrpCprofitFactors());
			CiInsureDemand ciInsureDemandDAA = prpmain.getCiInsureDemandDAA();
			if (ciInsureDemandDAA != null && StringUtils.isNotBlank(ciInsureDemandDAA.getRemark())) {
				throw new BizException("商业险平台：" + ciInsureDemandDAA.getRemark());
			}
			if (ciInsureDemandDAA != null && StringUtils.isNotBlank(ciInsureDemandDAA.getVehicleOwnerMessageType())) {
				if ("01".equals(ciInsureDemandDAA.getVehicleOwnerMessageType())) {
					_quoteResponse.setOtherMessage(
							StringUtils.join(_quoteResponse.getOtherMessage(), "未传送车辆过户标志，本次查询的车主名称与上张保单不一致"));
				} else if ("02".equals(ciInsureDemandDAA.getVehicleOwnerMessageType())) {
					_quoteResponse
							.setOtherMessage(StringUtils.join(_quoteResponse.getOtherMessage(), "本次查询的车主名称与上张保单不一致"));
				}
			}
			if (prpmain.getErrorMessageVo() != null && !"0000".equals(prpmain.getErrorMessageVo().getErrorCode())
					&& !"0004".equals(prpmain.getErrorMessageVo().getErrorCode())) {
				if ("0002".equals(prpmain.getErrorMessageVo().getErrorCode())) {
					_quoteResponse.setOtherMessage(StringUtils.join(_quoteResponse.getOtherMessage(), "调用定价系统异常：",
							prpmain.getErrorMessageVo().getErrorMessage()));
				} else if ("0001".equals(prpmain.getErrorMessageVo().getErrorCode())) {
					_quoteResponse.setOtherMessage(StringUtils.join(_quoteResponse.getOtherMessage(), "不报价：商业险正常报价信息：",
							prpmain.getErrorMessageVo().getErrorMessage()));
				} else if ("0003".equals(prpmain.getErrorMessageVo().getErrorCode())) {
					_quoteResponse.setOtherMessage(StringUtils.join(_quoteResponse.getOtherMessage(), "报价提示：",
							prpmain.getErrorMessageVo().getErrorMessage()));
				}
			}
			if (prpmain.getPrpCitemKinds() != null && prpmain.getPrpCitemKinds().size() > 0) {
				int i=0;
				for (PrpCitemKinds kind : prpmain.getPrpCitemKinds()) {
					for (KindPO po : bi.getKinds()) {
						if (kind.getKindCode().equals(po.getKindCode())) {
							biSumPremium += kind.getPremium();
							biSumamount += kind.getAmount() != null ? kind.getAmount() : 0;
							biSumBenchPremium += kind.getBenchMarkPremium() != null ? kind.getBenchMarkPremium() : 0;
							biSumNetPremium += kind.getNetPremium() != null ? kind.getNetPremium() : 0;
							BeanCopier.create(PrpCitemKinds.class, KindPO.class, false).copy(kind, po, null);
							po.setFlag(kind.getFlag());
							po.setStartDate(BaseUtil.dateTime2String(kind.getStartDate()));
							po.setEndDate(BaseUtil.dateTime2String(kind.getEndDate()));
							List<PrpCprofitDetails> factors = kind.getPrpCprofits()!=null?kind.getPrpCprofits().get(0).getPrpCprofitDetails():null;
							if(factors!=null && factors.size()>0) {
								for(PrpCprofitDetails factor: factors) {
									factor.setIndex(i++);
								}
							}
							po.setFactors(factors);
							bizKindItemSet(_quoteResponse.getQuoteResult(), kind,request);
						}
					}
				}
			}
			bi.setSumPremium(BaseUtil.getMoneyNumber(biSumPremium));
			bi.setStrSumPremium(String.format("%.2f", bi.getSumPremium()));
			bi.setSumBenchPremium(BaseUtil.getMoneyNumber(biSumBenchPremium));
			bi.setStrSumBenchPremium(String.format("%.2f", bi.getSumBenchPremium()));
			bi.setSumNetPremium(BaseUtil.getMoneyNumber(biSumNetPremium));
			bi.setStrSumNetPremium(String.format("%.2f", bi.getSumNetPremium()));
			bi.setSumTaxPremium(BaseUtil.getMoneyNumber(bi.getSumPremium() - bi.getSumNetPremium()));
			bi.setStrSumTaxPremium(String.format("%.2f", bi.getSumTaxPremium()));
			biDiscount = BaseUtil.getFormatNumber(bi.getSumPremium() / bi.getSumBenchPremium(), 8);
			bi.setDiscount(biDiscount);
			biSumDiscount = BaseUtil.getMoneyNumber(bi.getSumBenchPremium() - bi.getSumPremium());
			bi.setBiDemandNo(ciInsureDemandDAA.getDemandNo());
			bi.setBiDemandTime(ciInsureDemandDAA.getDemandTime() != null
					? BaseUtil.dateTime2String(ciInsureDemandDAA.getDemandTime(), "yyyy-MM-dd")
					: null);
			PrpCitemCarExt carExt = prpmain.getPrpCitemCarExt();
			if (carExt != null) {
				bi.setNoDamYearsBI(carExt.getNoDamYearsBI());
				bi.setLastDamagedBI(carExt.getLastDamagedBI());
				/**
				 * 商业险上年违法(次)
				 */
				bi.setLastDamagedCI(carExt.getLastDamagedCI());
				bi.setThisDamagedBI(carExt.getThisDamagedBI());
			}else {
				bi.setNoDamYearsBI(0);
				bi.setLastDamagedBI(0);
				/**
				 * 商业险上年违法(次)
				 */
				bi.setLastDamagedCI(0);
				bi.setThisDamagedBI(0);
			}
			final List<ClaimPayInfo> claimPayBI = Lists.newArrayList();
			if(prpmain.getCiInsureDemandPayListBI()!=null && prpmain.getCiInsureDemandPayListBI().size()>0) {
				prpmain.getCiInsureDemandPayListBI().forEach(demand->{
					ClaimPayInfo _claim = new ClaimPayInfo();
					BeanCopier.create(CiInsureDemandPayList.class, ClaimPayInfo.class, false).copy(demand, _claim, null);
					if(demand!=null) {
						_claim.setEndCaseDateTime(demand.getEndcCaseTime().getTime()>0?new Date(demand.getEndcCaseTime().getTime()):null);
						_claim.setLossDateTime(demand.getLossTime().getTime()>0?new Date(demand.getLossTime().getTime()):null);
					}
					_claim.setDemandNo(demand.getId()!=null ?demand.getId().getDemandNo():null);
					claimPayBI.add(_claim);
				});
			}
			_quoteResponse.setClaimListBI(claimPayBI!=null && claimPayBI.size()>0?claimPayBI:null);
			
			_quoteResponse.setBisAmount(bi.getSumPremium());
			_quoteResponse.setBisDiscount(bi.getDiscount());
		}
		// 处理交强险
		if (quoteResponse.getCiInsureVOList() != null && !quoteResponse.getCiInsureVOList().isEmpty()) {
			CiInsureVO ciInsureVO = quoteResponse.getCiInsureVOList().get(0);
			for (PrpCfixations pcf : ciInsureVO.getPrpCfixations()) {
				pcf.setPrefix("prpCfixationCITemp");
				pcf.setRiskCode("DZA");
			}
			if (main.getFixations() != null) {
				main.getFixations().addAll(ciInsureVO.getPrpCfixations());
			} else {
				main.setFixations(ciInsureVO.getPrpCfixations());
			}

			if (StringUtils.isNotBlank(ciInsureVO.getErrMessage())) {
				if (ciInsureVO.getErrMessage().split(",")[0] == "BDJY") {
					throw new BizException(ciInsureVO.getErrMessage().split(",")[1]);
				} else {
					throw new BizException("交强险平台：" + ciInsureVO.getErrMessage());
				}
			}
			ErrorMessageVo errorMessage = ciInsureVO.getErrorMessageVo();
			if (errorMessage != null && StringUtils.isNotBlank(errorMessage.getFlag())) {
				if ("1".equals(errorMessage.getFlag())) {
					throw new BizException("定价系统：" + errorMessage.getErrorMessage());
				} else if (!"0000".equals(errorMessage.getErrorCode())) {
					throw new BizException("不报价：交强险正常报价信息：" + errorMessage.getErrorMessage());
				}
			}
			CiInsureDemand ciInsureDemand = ciInsureVO.getCiInsureDemand();
			if ("1".equals(ciInsureDemand.getReinsureFlag()) || "2".equals(ciInsureDemand.getReinsureFlag())
					|| "3".equals(ciInsureDemand.getReinsureFlag())) {
				throw new BizException("交强险平台：该车辆重复投保。");
			}

			if ("01".equals(ciInsureDemand.getNoVehicleMessageType())) {
				throw new BizException("交强险平台:非新车请核实是否为已上牌或过户车辆!");
			}
//			if ("1".equals(quoteResponse.getcIInsureMotorFlag())) {
//				if ("01".equals(ciInsureDemand.getVehicleOwnerMessageType())) {
//					throw new BizException("交强险平台：未传送车辆过户标志，本次查询的车主名称与上张保单不一致!");
//				} else if ("02".equals(ciInsureDemand.getVehicleOwnerMessageType())) {
//					throw new BizException("交强险平台：传送了车辆过户标志，本次查询的车主名称与上张保单一致!");
//				}
//			}
			ciSumPremium = ciInsureDemand.getPremium();
			ciDiscount = BaseUtil.getFormatNumber(ciSumPremium / ciInsureDemand.getBasePremium(), 8);
			ciSumDiscount = ciInsureDemand.getBasePremium() - ciSumPremium;
			PrpCitemKinds kind = quoteResponse.getCiInsureVOList().get(0).getPrpCitemKinds().get(0);

			BeanCopier.create(PrpCitemKinds.class, CIPO.class, false).copy(kind, ci, null);
			ci.setPremium(ciInsureDemand.getPremium());
			ci.setBenchMarkPremium(ciInsureDemand.getBasePremium());
			ci.setDisCount(ciDiscount);
			ci.setAdjustRate(BaseUtil.getFormatNumber(ciInsureDemand.getPeccancyCoeff()
					.add(ciInsureDemand.getClaimCoeff()).add(new BigDecimal("1")).doubleValue(), 4));
			ci.setFlag(ci.getFlag() != null ? ci.getFlag().trim() : ci.getFlag());
			ci.setDemandNo(ciInsureDemand.getDemandNo());
			ci.setDemandTime(ciInsureDemand.getDemandTime() != null
					? BaseUtil.dateTime2String(ciInsureDemand.getDemandTime(), "yyyy-MM-dd")
					: null);
			ci.setRestricFlag(ciInsureDemand.getRestricFlag());
			ci.setPreferentialDay(ciInsureDemand.getPreferentialDay());
			ci.setPreferentialPremium(ciInsureDemand.getPreferentialPremium());
			ci.setPreferentialFormula(ciInsureDemand.getPreferentialFormula());
			ci.setLastyearenddate(ciInsureDemand.getLastyearenddate());
			ci.setRateRloatFlag(ciInsureDemand.getRateRloatFlag());
			/**
			 * A1--连续1年未出险 A2--连续2年未出险 A3--连续3年未出险 ciInsureDemandPays出险记录
			 * A5 上一个年度发生两次及或两次以上有责任道路交通事故
			 */
			ci.setClaimAdjustReason(ciInsureDemand.getClaimAdjustReason());
			/**
			 * V1上一个年度没有道路交通安全违法行为
			 */
			ci.setPeccancyAdjustReason(ciInsureDemand.getPeccancyAdjustReason());
			// CiCarShipTax ciCarShipTax = ciInsureVO.getCiCarShipTax();
			CiInsureTax ciInsureTax = ciInsureVO.getCiInsureTax();
			if (ciInsureTax != null) {
				ci.getTax().setTaxPayerName(ciInsureTax.getTaxPayerName());
				ci.getTax().setTaxPayerNumber(ciInsureTax.getTaxPayerIdentificationCode());
				String taxType = "";
				if ("T".equals(ciInsureTax.getTaxConditionCode())) {
					taxType = "1";// 正常缴税
				} else if ("E".equals(ciInsureTax.getTaxConditionCode())) {
					taxType = "2";// 免税
				} else if ("C".equals(ciInsureTax.getTaxConditionCode())) {
					taxType = "3";// 减税
				} else if ("P".equals(ciInsureTax.getTaxConditionCode())) {
					taxType = "4";// 已完税
				} else if ("D".equals(ciInsureTax.getTaxConditionCode())) {
					taxType = "5";// 有争议
				} else if ("R".equals(ciInsureTax.getTaxConditionCode())) {
					taxType = "6";// 拒缴
				} else {
					taxType = "7";// 其他
				}
				ci.getTax().setTaxType(taxType);
				if (ciInsureTax.getCiInsureAnnualTaxes() != null && ciInsureTax.getCiInsureAnnualTaxes().size() > 0) {
					CiInsureAnnualTaxes ciInsureAnnualTaxe = ciInsureTax.getCiInsureAnnualTaxes().get(0);
					ci.getTax().setTaxUnit("2".equals(ciInsureAnnualTaxe.getTaxUnitTypeCode()) ? "吨/辆" : "辆/年");
					if (StringUtils.isNotBlank(ciInsureAnnualTaxe.getUnitRate()))
						ci.getTax().setTaxUnitAmount(Double.valueOf(ciInsureAnnualTaxe.getUnitRate()));
					ci.getTax().setPayStartDate(ciInsureAnnualTaxe.getTaxStartDate());
					ci.getTax().setPayEndDate(ciInsureAnnualTaxe.getTaxEndDate());
					ci.getTax().setThisPayTax(ciInsureTax.getAnnualTaxDue());
					ci.getTax().setPrePayTax(ciInsureTax.getSumTaxDefault());
					ci.getTax().setDelayPayTax(ciInsureTax.getSumOverdue());
					ci.getTax().setSumPayTax(ciInsureTax.getSumTax());
					ci.getTax().setTaxRegistryNumber(quoteResponse.getTaxRegistryNumber());
					if ("2".equals(taxType) || "3".equals(taxType)) {
						CiInsureDerateTaxes ciInsureDerateTaxes = ciInsureTax.getCiInsureAnnualTaxes().get(0)
								.getCiInsureDerateTaxes().get(0);
						// 减免原因
						String dueCode = ciInsureDerateTaxes.getDeductionDueCode();
						switch (dueCode) {
						// 具备减免税证明
						case "C":
							ci.getTax().setTaxAbateReason("01");
							break;
						// 拖拉机
						case "F":
							ci.getTax().setTaxAbateReason("03");
							break;
						// 军队、武警专用车
						case "A":
							ci.getTax().setTaxAbateReason("02");
							break;
						// 警车
						case "P":
							ci.getTax().setTaxAbateReason("04");
							break;
						// 外国使领馆、国际组织及其人员
						case "D":
							ci.getTax().setTaxAbateReason("05");
							break;
						// 能源减免
						case "E":
							ci.getTax().setTaxAbateReason("06");
							break;
						// 其他
						case "O":
							ci.getTax().setTaxAbateReason("99");
							break;
//							if ("11,12,13,14".indexOf(ci.getTax().getTaxAbateReason())) > -1) {
//								break;
//							} else {
//								ci.getTax().setTaxAbateReason("99");
//								break;
//							}
						}
						// 减免税方案代码
						String dueType = ciInsureDerateTaxes.getDeductionDueType();
						if ("P".equals(dueType)) {// 按比例减免
							ci.getTax().setTaxAbateType("1");
							// 减免比例
							ci.getTax().setTaxAbateRate(String.valueOf(BaseUtil
									.getFormatNumber(ciInsureDerateTaxes.getDeductionDueProportion() * 100, 0)));
						} else if ("A".equals(dueType)) {// 按金额减免
							ci.getTax().setTaxAbateType("2");
							ci.getTax().setTaxAbateAmount(ciInsureDerateTaxes.getDeduction());
						}
						// 减免税凭证号
						if (StringUtils.isNotBlank(ciInsureDerateTaxes.getDeductionDocumentNumber())) {
							ci.getTax().setDutyPaidProofNo_1(ciInsureDerateTaxes.getDeductionDocumentNumber());
							ci.getTax().setDutyPaidProofNo(ciInsureDerateTaxes.getDeductionDocumentNumber());
						}
						// 开具减免税凭证的税务机关代码
						if (StringUtils.isBlank(ci.getTax().getTaxComCode())
								&& StringUtils.isNotBlank(ciInsureDerateTaxes.getTaxDepartmentCode())) {
							ci.getTax().setTaxComCode(ciInsureDerateTaxes.getTaxDepartmentCode());
						}
						// 开具减免税凭证的税务机关名称
						if (StringUtils.isBlank(ci.getTax().getTaxComName())
								&& StringUtils.isNotBlank(ciInsureDerateTaxes.getTaxDepartment())) {
							ci.getTax().setTaxComName(ciInsureDerateTaxes.getTaxDepartment());
						}

						if ("2".equals(taxType)) {
							ci.getTax().setSumPayTax(0d);
						}
					} else if ("4".equals(taxType)) {// 完税
						ci.getTax().setDutyPaidProofNo(null);
						Calendar calendar = Calendar.getInstance();
						calendar.setTime(request.getForceStartTime());
						int insureYear =calendar.get(Calendar.YEAR);
						calendar.setTimeInMillis(System.currentTimeMillis());
						int operateYear = calendar.get(Calendar.YEAR);
						// 开具完税凭证的税务机关代码
						if (StringUtils.isNotBlank(ciInsureAnnualTaxe.getTaxDepartmentCode())) {
							ci.getTax().setTaxComCode(ciInsureAnnualTaxe.getTaxDepartmentCode());
						}else {
							ci.getTax().setTaxComCode(null);
						}
						// 开具减免税凭证的税务机关名称
						if (StringUtils.isNotBlank(ciInsureAnnualTaxe.getTaxDepartment())) {
							ci.getTax().setTaxComName(ciInsureAnnualTaxe.getTaxDepartment());
						}
						// 完税凭证号码
						if (StringUtils.isNotBlank(ciInsureAnnualTaxe.getTaxDocumentNumber())) {
							ci.getTax().setDutyPaidProofNo_2(ciInsureAnnualTaxe.getTaxDocumentNumber());
							ci.getTax().setDutyPaidProofNo(ci.getTax().getDutyPaidProofNo_2());
						}else {
							//解决跨年不能提前买车船税的问题,需要人保上年续保商业保单号才能提交
							if(insureYear>operateYear && StringUtils.isNotBlank(main.getRenewalPolicyNo()) 
//									&& main.getRenewalPolicyNo().contains("DAA")
									) {
								//关于在保险公司完税（车船税）的业务，完税录入的规则如下：
								//“完税凭证号”的格式统一设置为“LS+已缴纳系统上线实施当前年税款的保单号”，
								//“统一开具完税凭证机关名称”的格式统一设置为“LSWS+已缴纳税款实施当前年税款的保单所对应保险机构的四位英文缩写
								//（例如人保已缴纳税款保单：LSWSPICC）”。） 
								ci.getTax().setTaxComName("LSWSPICC");
	//							ci.getTax().setTaxType("4");
								String paidProofNo = "LS"+main.getRenewalPolicyNo();
								ci.getTax().setDutyPaidProofNo(paidProofNo);
								ci.getTax().setDutyPaidProofNo_2(paidProofNo);
							}
						}
					} else if("1".equals(taxType)) {
						ci.getTax().setTaxComCode(rbSysConfig.getTaxComCode());
						ci.getTax().setTaxComName(rbSysConfig.getTaxComName());
					}else {
						ci.getTax().setDutyPaidProofNo(null);
						ci.getTax().setDutyPaidProofNo_2(null);
					}
				}
			}
			//交强理赔信息
			final List<ClaimPayInfo> claimPayCI = Lists.newArrayList();
			if(ciInsureVO.getCiInsureDemandPayList()!=null && ciInsureVO.getCiInsureDemandPayList().size()>0) {
				ciInsureVO.getCiInsureDemandPayList().forEach(demand->{
					ClaimPayInfo _claim = new ClaimPayInfo();
					BeanCopier.create(CiInsureDemandPayList.class, ClaimPayInfo.class, false).copy(demand, _claim, null);
					_claim.setEndCaseDateTime(demand.getEndcCaseTime() != null && demand.getEndcCaseTime().getTime() > 0
							? new Date(demand.getEndcCaseTime().getTime())
							: null);
					_claim.setLossDateTime(demand.getLossTime() != null && demand.getLossTime().getTime() > 0
							? new Date(demand.getLossTime().getTime())
							: null);
					_claim.setDemandNo(demand.getId()!=null ?demand.getId().getDemandNo():null);
					claimPayCI.add(_claim);
				});
			}
			_quoteResponse.setClaimListCI(claimPayCI!=null && claimPayCI.size()>0?claimPayCI:null);
			
			_quoteResponse.setTax(ci.getTax() != null ? ci.getTax().getSumPayTax() : 0d);
			_quoteResponse.setForBasicAmount(ci.getBenchMarkPremium());
			_quoteResponse.setForDiscount(ci.getDisCount());
			_quoteResponse.setJiaoqiang(ci.getPremium());
		}
		_quoteResponse.setBusinessStatus(1);
		_quoteResponse.setStatusMessage("ok");
		_quoteResponse.setBaojiaNum(main.getRandomProposalNo());
		_quoteResponse.setUserId(request.getUserId());
		_quoteResponse.setWsId(request.getWsId());
		_quoteResponse.setBizId(request.getBizId());
		// 增加2017年底活动送补漆、洗车
		// 免费洗车特约：9901149
		// 喷漆：9901262
		// （一）划痕补漆服务项目  
		// 1、赠送承保条件
		// 对符合以下条件的车险业务，由分公司承担划痕补漆服务的费用：
		// （1）签单日期在考核期的家庭自用车车险业务；
		// （2）被保险人均为个人客户，七座及以下的客车；
		// （3）业务范围包括续保和R类(续保)，同时投保交强险和商业险，且投保车损险和商业三责险，其中商三责险保额100万（含）及以上；
		// （4）商业险单面保费不少于2500元；
		// （5）上一个保险年度出险2次及以下；
		// （6）在我司全渠道投保的客户。
		// 2、划痕补漆项目类型
		// 根据商业险单面保费规模，差异化赠送划痕补漆服务，具体如下：
		// 卡类 面值 对应商业车险单面保费条件
		// A 1500 15000元（含）以上
		// B 800 8000（含）-15000元
		// C 500 2500（含）-8000元
		// 3、服务有效期
		// 从成功领取之日起一年有效期。
		// （二）”i洗车”服务项目
		// 1、赠送承保条件
		// 对符合以下条件的车险业务，由分公司承担洗车服务的费用：
		// （1）录入i洗车特约（特约代码：9901149）的家用车续R类业务；
		// （2）被保险人为个人客户，七座及以下的客车，同时投保交强险和商业险；
		// （3）商业险单面保费在2500元（含）以上；
		// （4）上年出险次数不超过4次（不含4次）；
		// （5）投保渠道为全渠道的车险业务；
		// （6）业务范围包括续保和R类业务(续保)，其中商业三责险保额100万（含）及以上。
		// 2、项目服务内容
		// 全年12次免费洗车。
		// R类业务不需要关心
		// 2017-10-1 到2017-12-31有效
		//新车不参加活动，新车判断条件：满足初登日期距起保日期一年及一年内算新车。脱保不算新车
		//不设有效期,update by 2018-01-02
		List<PromotionPO> promotions = Lists.newArrayList();
//		if (main.getCurrentDate().getYear() == 2017 && main.getCurrentDate().getMonthValue() >= 10) {
		if("44010000".equals(request.getCityId())) {//广州才有活动
			if (vehicle.getSeatCount() <= 7 && request.getBusStartTime() != null && request.getForceStartTime() != null
					&& DateUtils.add(request.getUserVehicleInfo().getFirstRegisterDate(),Calendar.MONTH,9).compareTo(request.getBusStartTime())<=0
					&& request.getQuote().getThirdPartyAmount() != null
					&& request.getQuote().getThirdPartyAmount().doubleValue() >= 1000000
					&& bi.getSumPremium().doubleValue() >= 2500) {
				// 上一个保险年度出险2次及以下
				int biPayCount = bi.getLastDamagedBI() != null ? bi.getLastDamagedBI().intValue() : 0;
//				int ciPayCount = quoteResponse.getCiInsureVOList().get(0).getCiInsureDemandPayList() != null
//						? quoteResponse.getCiInsureVOList().get(0).getCiInsureDemandPayList().size()
//						: 0;
				int payCount = biPayCount ;
				// 洗车
				if (payCount < 4) {
					AgreePO ixc = new AgreePO();
					ixc.setSerialNo(agreeList.size() + 1);
					ixc.setIndex(ixc.getSerialNo() - 1);
					ixc.setClauseCode("9901149");
					ixc.setClauseName("i洗车专属特约");
					ixc.setClauses("投保成功将加入“i洗车”项目，详情请关注“广州人保财险”微信公众号或咨询95518。");
					agreeList.add(ixc);
					promotions.add(new PromotionPO("i洗车","投保成功将加入“i洗车”项目，详情请关注“广州人保财险”微信公众号或咨询95518。"));
				}
				// 补漆
				if (request.getQuote().getDamage() != null && payCount <= 2) {
					AgreePO iwy = new AgreePO();
					iwy.setSerialNo(agreeList.size() + 1);
					iwy.setIndex(iwy.getSerialNo() - 1);
					iwy.setClauseCode("9901262");
					iwy.setClauseName("“i无忧”特约");
					iwy.setClauses("投保成功将加入“i无忧”项目，详情请关注“广州人保财险”微信公众号或咨询95518。");
					agreeList.add(iwy);
					promotions.add(new PromotionPO("i无忧","投保成功将加入“i无忧”项目，详情请关注“广州人保财险”微信公众号或咨询95518。"));
				}
			}
		}
//		}
		_quoteResponse.setPromotions(promotions!=null && promotions.size()>0?promotions:null);
		_quoteResponse.setEcho(request.getEcho());
		//用户输入关系人名称和系统不一致
		if("invalid".equals(privy.getPrivyStatus())) {
			_quoteResponse.setTaxError(1);
		}
		//发送报价
		messageHandler.sendQuote(_quoteResponse);
		StageProposal stage = new StageProposal();
		SummaryProposal summary = new SummaryProposal();
		summary.setCarChecker(rbSysConfig.getHandler1Code());
		summary.setProjectCode(rbSysConfig.getProjectCode());
		summary.setProjectName(rbSysConfig.getProjectName());
		summary.setOperatorCode(rbSysConfig.getOperatorCode());
		summary.setOperatorName(rbSysConfig.getOperatorName());
		summary.setArgueSolution(rbSysConfig.getArgueSolution());
		summary.setArbitBoardName(rbSysConfig.getArbitBoardName());
		summary.setArbitBoardNameDes(rbSysConfig.getArbitBoardNameDes());
		summary.setSumAmount(BaseUtil.getMoneyNumber(biSumamount));
		summary.setDiscount(BaseUtil.getFormatNumber(biDiscount, 4));
		summary.setSumPremium(BaseUtil.getMoneyNumber(biSumPremium));
		summary.setSumDiscount(BaseUtil.getMoneyNumber(biSumDiscount));
		summary.setSumAmountCI(BaseUtil.getMoneyNumber(ciSumamount));
		summary.setDiscountCI(BaseUtil.getFormatNumber(ciDiscount, 4));
		summary.setSumPremiumCI(BaseUtil.getMoneyNumber(ciSumPremium));
		summary.setSumDiscountCI(BaseUtil.getMoneyNumber(ciSumDiscount));
		stage.setBi(bi);
		stage.setCi(ci);
		stage.setMain(main);
		stage.setQuoteResponse(_quoteResponse);
		stage.setStrOther(strOther);
		stage.setStrPrivy(strPrivy);
		stage.setStrVehicle(strVehicle);
		stage.setSummary(summary);
//		stage.setAgrees(agreeList);
		
		strAgree=  compiler.compile(mustacheTemplateLoader.getTemplate("quote_agree")).execute(new Object() {
			@SuppressWarnings("unused")
			List<AgreePO> agrees = agreeList;
		});
		stage.setStrAgree(strAgree);
		this.cache.putProposal(main.getRandomProposalNo(), stage);
		//不再通知客户端
		_quoteResponse.setBusinessStatus(2000);
		return _quoteResponse;
	}
	
	
	public class PlanTemplate {
		List<PayDetailQuote> plans;

		public PlanTemplate(List<PayDetailQuote> plans) {
			this.plans = plans;
		}

		public List<PayDetailQuote> getPlans() {
			return plans;
		}

		public void setPlans(List<PayDetailQuote> plans) {
			this.plans = plans;
		}
	}

	public List<PayDetailQuote> refreshPlan(String strBody) throws Exception {
		ResponseModel<String> jsonResponse = okHttpClientService.postHtml(urlConfig.getCplanUrl(), strBody,
				String.class);
		if (!jsonResponse.isSuccessful() || StringUtils.isBlank(jsonResponse.getBody())) {
			throw new BizException("生成缴费计划失败");
		}
		if ("0".equals(jsonResponse.getBody())) {
			throw new BizException("此保单不允许分期缴费");
		}
		Model<PayDetailQuote> response = JsonUtils.parseJson(jsonResponse.getBody(),
				new TypeReference<Model<PayDetailQuote>>() {
				});
		if (response != null && response.getData() != null && response.getData().size() > 0) {
			return response.getData();
		}
		return null;
	}

	public void quote2Proposal(String strBody, ApplyQuoteResponse quoteResponse) throws Exception {
		ResponseModel<String> jsonResponse = okHttpClientService.postHtml(urlConfig.getProposalUrl(), strBody,
				String.class);
		if (!jsonResponse.isSuccessful() || StringUtils.isBlank(jsonResponse.getBody())) {
			throw new BizException("投保单保存失败");
		}
		String result = jsonResponse.getBody();
		String[] arrResult = result.split("=");
		if (arrResult.length == 2) {
			if ("null".equals(arrResult[1])) {
				throw new BizException("此单已被删除，不能被保存!请重新录入");
			} else {
				throw new BizException(arrResult[1]);
			}
		} else if (arrResult.length == 1) {
			arrResult = result.split("\\$");
			if (arrResult.length == 2) {
				quoteResponse.setOtherMessage(StringUtils.join(quoteResponse.getOtherMessage(), arrResult[1]));
			}
			arrResult = arrResult[0].split(",");
			if ("checkFlag".equals(arrResult[0])) {
				throw new BizException("该投保单已经提交初审/核保，不允许修改");
			}
			if (arrResult.length == 2) {
				quoteResponse.setBiNo(arrResult[0]);
				quoteResponse.setCiNo(arrResult[1]);
			} else if (arrResult.length == 1) {
				if (arrResult[0].contains("DAA")) {
					quoteResponse.setBiNo(arrResult[0]);
				} else {
					quoteResponse.setCiNo(arrResult[0]);
				}
			}
			quoteResponse.setBusinessStatus(1);
		}
	}

	private QuoteResponse picsCheck(CiInsureDemandCheckVo biCheck, CiInsureDemandCheckVo ciCHeck, OtherQuote other,
			String strBody) throws Exception {
		List<CaptchaVO> captchas = Lists.newArrayList();
		if (biCheck != null && StringUtils.isNotBlank(biCheck.getCheckCode())) {
			CaptchaVO vo = new CaptchaVO();
			vo.setType(1);
			vo.setData(biCheck.getCheckCode());
			vo.setName("BI");
			captchas.add(vo);
		}
		if (ciCHeck != null && StringUtils.isNotBlank(ciCHeck.getCheckCode())) {
			CaptchaVO vo = new CaptchaVO();
			vo.setType(1);
			vo.setData(ciCHeck.getCheckCode());
			vo.setName("CI");
			captchas.add(vo);
		}
		captchas = picsCaptchaService.recognition(captchas);
		if (captchas != null) {
			for (CaptchaVO vo : captchas) {
				if ("BI".equals(vo.getName())) {
					other.setBiCheckAnswer(vo.getText());
				}
				if ("CI".equals(vo.getName())) {
					other.setCiCheckAnswer(vo.getText());
				}
			}
		}
		strBody = strBody + compiler.compile(mustacheTemplateLoader.getTemplate("quote_check")).execute(other);
		ResponseModel<Model<QuoteResponse>> jsonResponse = okHttpClientService.postJson(urlConfig.getQuoteUrl(),
				strBody, new TypeReference<Model<QuoteResponse>>() {
				});
		if (jsonResponse == null || !jsonResponse.isSuccessful() || jsonResponse.getBody() == null) {
			throw new SystemException("系统异常,报价失败");
		}

		if (StringUtils.isNotBlank(jsonResponse.getBody().getMsg())) {
			String[] msgs = jsonResponse.getBody().getMsg().split(",");
			if ("0".equals(msgs[0])) {
				throw new BizException(msgs[1]);
			} else if ("1".equals(msgs[0])) {
				throw new VehicleCodeException(jsonResponse.getBody().getMsg());
			} else {
				throw new BizException(jsonResponse.getBody().getMsg());
			}
		}
		QuoteResponse quoteResponse = jsonResponse.getBody().getData().get(0);
		CiInsureDemandCheckVo ciInsureDemandCheckVo = quoteResponse.getBiInsuredemandVoList() != null
				&& !quoteResponse.getBiInsuredemandVoList().isEmpty()
						? quoteResponse.getBiInsuredemandVoList().get(0).getCiInsureDemandCheckVo()
						: null;
		CiInsureDemandCheckVo ciInsureDemandCheckCIVo = quoteResponse.getCiInsureVOList() != null
				&& !quoteResponse.getCiInsureVOList().isEmpty()
						? quoteResponse.getCiInsureVOList().get(0).getCiInsureDemandCheckVo()
						: null;

		if ((ciInsureDemandCheckVo != null && "1".equals(ciInsureDemandCheckVo.getRenewalFlag()))
				|| (ciInsureDemandCheckCIVo != null && "1".equals(ciInsureDemandCheckCIVo.getRenewalFlag()))) {
			return null;
		}
		return quoteResponse;
	}

	/**
	 * 辅助核保
	 */
	public AssistResponse assistCheck(String strBody) throws Exception {
		ResponseModel<Model<AssistResponse>> jsonResponse = okHttpClientService.postJson(urlConfig.getAssistUrl(),
				strBody, new TypeReference<Model<AssistResponse>>() {
				});
		if (jsonResponse.isSuccessful() && jsonResponse.getBody() != null && jsonResponse.getBody().getData() != null
				&& jsonResponse.getBody().getData().size() > 0) {
			return jsonResponse.getBody().getData().get(0);
		}
		throw new BizException(jsonResponse.getBody() != null && StringUtils.isNotBlank(jsonResponse.getBody().getMsg())
				? jsonResponse.getBody().getMsg()
				: "辅助核保错误:R指标计算错误，请检查所填写信息并重新计算");
	}

	/**
	 * 计算跟单费用
	 */
	public SummaryProposal getCseller(String strBody, SummaryProposal summary) throws Exception {
		ResponseModel<String> jsonResponse = okHttpClientService.postHtml(urlConfig.getFeeUrl(), strBody, String.class);
		if (!jsonResponse.isSuccessful() || StringUtils.isBlank(jsonResponse.getBody())) {
			throw new BizException("计算跟单费用错误");
		}
		String body = jsonResponse.getBody();
		if (body.indexOf("maxfee") != -1) {
			String varmaxfee = body.substring(body.indexOf("{"));
			SummaryProposal fee = new SummaryProposal();
			if (StringUtils.isNotBlank(varmaxfee)) {
				fee = JsonUtils.parseJson(varmaxfee.replaceAll("'", "\""), SummaryProposal.class);
				summary.setSellerCertificateNo(fee.getSellerCertificateNo());
				summary.setSellerFeeUpdateFlag(fee.getSellerFeeUpdateFlag());
				summary.setSellerMaxFee(fee.getSellerMaxFee());
				summary.setSellerMaxFeeCi(fee.getSellerMaxFeeCi());
				summary.setSellerMaxFeeGB(fee.getSellerMaxFeeGB());
				summary.setSellerMaxFeeGb(fee.getSellerMaxFeeGb());
				summary.setSellerMaxFeeGB1(fee.getSellerMaxFeeGB1());
				summary.setSellerMaxFeeGc(fee.getSellerMaxFeeGc());
				summary.setSellerMaxFeeGC(fee.getSellerMaxFeeGC());
				summary.setSellerMaxFeeGC1(fee.getSellerMaxFeeGC1());
				summary.setSellerMaxFeeGr(fee.getSellerMaxFeeGr());
				summary.setSellerMaxFeeGR(fee.getSellerMaxFeeGR());
				summary.setSellerMaxFeeGR1(fee.getSellerMaxFeeGR1());
				summary.setSellerMaxFeeGr(fee.getSellerMaxFeeGr());
				summary.setSellerMaxFeeGS(fee.getSellerMaxFeeGS());
				summary.setSellerMaxFeeGs(fee.getSellerMaxFeeGs());
				summary.setSellerMaxFeeGS1(fee.getSellerMaxFeeGS1());
				summary.setSellerMaxFeeGT(fee.getSellerMaxFeeGT());
				summary.setSellerMaxFeeGt(fee.getSellerMaxFeeGt());
				summary.setSellerMaxFeeGT1(fee.getSellerMaxFeeGT1());
			}
			String anciIndiConfQueryVos = body.substring(body.indexOf("["));
			if (StringUtils.isNotBlank(anciIndiConfQueryVos)) {
				fee.setVos(JsonUtils.parseJson(anciIndiConfQueryVos.replaceAll("'", "\""),
						new TypeReference<List<AnciIndiConfQueryVo>>() {
						}));
				summary.setVos(fee.getVos());
			}
			return fee;
		}

		return null;
	}

	/**
	 * 拆分商业险费用
	 */
	public List<Seller> feeBi(String strBody, StageProposal stage) throws Exception {
		SummaryProposal summary = stage.getSummary();
		String cityId = stage.getQuoteResponse()!=null?stage.getQuoteResponse().getCityId():null;
		ResponseModel<Model<Seller>> jsonResponse = okHttpClientService.postJson(urlConfig.getBIFeeUrl(), strBody,
				new TypeReference<Model<Seller>>() {
				});
		if (!jsonResponse.isSuccessful() || jsonResponse.getBody() == null || jsonResponse.getBody().getData() == null
				|| jsonResponse.getBody().getData().isEmpty()) {
			throw new BizException("商业险费用拆分失败");
		}
		double sumrate = 0;
		double sumfee = 0;
		int index = 0;
		for (final Seller seller : jsonResponse.getBody().getData()) {
			seller.setIndex(index++);
			if (seller.getSellfeerate() == null) {
				if ("44010000".equals(cityId)) {
					if ("0".equals(seller.getBusinessnature())) {
						if (summary.getSellerMaxFeeGS1() != null && summary.getSellerMaxFeeGS1() > 0)
							seller.setSellfeerate(summary.getSellerMaxFeeGS1());
					} else if ("1".equals(seller.getBusinessnature()) || "2".equals(seller.getBusinessnature())
							|| "3".equals(seller.getBusinessnature())) {
						if (summary.getSellerMaxFeeGR1() != null && summary.getSellerMaxFeeGR1() > 0)
							seller.setSellfeerate(summary.getSellerMaxFeeGR1());
					} else {
						if (summary.getSellerMaxFeeGT1() != null && summary.getSellerMaxFeeGT1() > 0)
							seller.setSellfeerate(summary.getSellerMaxFeeGT1());
					}
				} else {
					seller.setSellfeerate("1".equals(seller.getMainflag()) ? summary.getSellerMaxFeeGB1()
							: summary.getSellerMaxFeeGb());
				}
			}
			
//			//修改为个人代理人。李阿丽
//			if (StringUtils.isBlank(seller.getAgentcode())) {
//				seller.setBusinessnature("1");
//				seller.setSellfeetype("01");
//				seller.setSellfeerate(0d);
//			}
			if("1".equals(seller.getMainflag())) {
				seller.setSellerno(rbSysConfig.getAgentSellerCode());
				seller.setSellername(rbSysConfig.getAgentSellerName());
				seller.setSellertype(rbSysConfig.getAgentSellerType());
			}
//			if (StringUtils.isNotBlank(seller.getAgentcode())) {
//				seller.setSellerno(rbSysConfig.getAgentSellerCode());
//				seller.setSellername(rbSysConfig.getAgentSellerName());
//				seller.setSellertype(rbSysConfig.getAgentSellerType());
//			}
			
			//优先配置数据
			if(rbSysConfig.getBiSeller()!=null && rbSysConfig.getBiSeller().size()>0) {
				rbSysConfig.getBiSeller().forEach(s->{
					if(s.getIndex()==seller.getIndex()) {
						BeanUtils.copyProperties(s, seller,getNullPropertyNames(s));
					}
				});
			}
			seller.setSellfeetype_select(seller.getSellfeetype());
			seller.setBusinessnature_select(seller.getBusinessnature());
			seller.setProposalno(seller.getId()!=null?seller.getId().getProposalno():null);
			double sellFee = BaseUtil.getMoneyNumber(seller.getSellfeerate() / 100
					* (summary.getSumPremium() != null ? summary.getSumPremium() - summary.getSumPremium() * 0.06 / 1.06
							: 0));
			seller.setSellfee(sellFee);
			
			sumrate += seller.getSellfeerate() != null ? seller.getSellfeerate() : 0;
			sumfee += seller.getSellfee() != null ? seller.getSellfee() : 0;
		}
		if (summary.getCommissions() != null) {
			for (Commissions commission : summary.getCommissions()) {
				if ("DAA".equals(commission.getRiskCode())) {
					commission.setCostRate(sumrate);
					commission.setCostFee(sumfee);
					break;
				}
			}
		}
		summary.setBiSeller(jsonResponse.getBody().getData());
		return jsonResponse.getBody().getData();
	}

	private static String[] getNullPropertyNames(Object source) {
        final BeanWrapper src = new BeanWrapperImpl(source);
        java.beans.PropertyDescriptor[] pds = src.getPropertyDescriptors();

        Set<String> emptyNames = new HashSet<String>();
        for(java.beans.PropertyDescriptor pd : pds) {
            Object srcValue = src.getPropertyValue(pd.getName());
            if (srcValue == null) emptyNames.add(pd.getName());
        }
        String[] result = new String[emptyNames.size()];
        return emptyNames.toArray(result);
    }
	
	/**
	 * 拆分交强险费用
	 */
	public List<Seller> feeCi(String strBody, StageProposal stage) throws Exception {
		SummaryProposal summary = stage.getSummary();
		String cityId = stage.getQuoteResponse()!=null?stage.getQuoteResponse().getCityId():null;
		ResponseModel<Model<Seller>> jsonResponse = okHttpClientService.postJson(urlConfig.getCIFeeUrl(), strBody,
				new TypeReference<Model<Seller>>() {
				});
		if (!jsonResponse.isSuccessful() || jsonResponse.getBody() == null || jsonResponse.getBody().getData() == null
				|| jsonResponse.getBody().getData().isEmpty()) {
			throw new BizException("交强险费用拆分失败");
		}
		double sumrate = 0;
		double sumfee = 0;
		int index = 0;
		for (Seller seller : jsonResponse.getBody().getData()) {
			seller.setIndex(index++);
			if (seller.getSellfeerate() == null) {
				if ("44010000".equals(cityId)) {
					if ("0".equals(seller.getBusinessnature())) {
						seller.setSellfeerate(summary.getSellerMaxFeeGs());
					} else if ("1".equals(seller.getBusinessnature()) || "2".equals(seller.getBusinessnature())
							|| "3".equals(seller.getBusinessnature())) {
						seller.setSellfeerate(summary.getSellerMaxFeeGr());
					} else {
						seller.setSellfeerate(summary.getSellerMaxFeeGt());
					}
				} else {
					seller.setSellfeerate(
							"1".equals(seller.getMainflag())
									? summary.getSellerMaxFeeGC1()
									: summary.getSellerMaxFeeGc());
				}
			}
			if("1".equals(seller.getMainflag())) {
				seller.setSellerno(rbSysConfig.getAgentSellerCode());
				seller.setSellername(rbSysConfig.getAgentSellerName());
				seller.setSellertype(rbSysConfig.getAgentSellerType());
			}
//			if (StringUtils.isNotBlank(seller.getAgentcode())) {
//				seller.setSellerno(rbSysConfig.getAgentSellerCode());
//				seller.setSellername(rbSysConfig.getAgentSellerName());
//				seller.setSellertype(rbSysConfig.getAgentSellerType());
//			}
			//优先配置数据
			if(rbSysConfig.getCiSeller()!=null && rbSysConfig.getCiSeller().size()>0) {
				rbSysConfig.getCiSeller().forEach(s->{
					if(s.getIndex()==seller.getIndex()) {
						BeanUtils.copyProperties(s, seller,getNullPropertyNames(s));
					}
				});
			}
			seller.setSellfeetype_select(seller.getSellfeetype());
			seller.setBusinessnature_select(seller.getBusinessnature());
			seller.setProposalno(seller.getId()!=null?seller.getId().getProposalno():null);
			
			double sellFee = BaseUtil.getMoneyNumber(seller.getSellfeerate() / 100
					* (summary.getSumPremiumCI() != null
							? summary.getSumPremiumCI() - summary.getSumPremiumCI() * 0.06 / 1.06
							: 0));
			seller.setSellfee(sellFee);
			
			sumrate += seller.getSellfeerate() != null ? seller.getSellfeerate() : 0;
			sumfee += seller.getSellfee() != null ? seller.getSellfee() : 0;
			// seller.setPrefix("prpCSellersCi");
		}
		if (summary.getCommissions() != null) {
			for (Commissions commission : summary.getCommissions()) {
				if ("DZA".equals(commission.getRiskCode())) {
					commission.setCostRate(sumrate);
					commission.setCostFee(sumfee);
					break;
				}
			}
		}
		summary.setCiSeller(jsonResponse.getBody().getData());
		return jsonResponse.getBody().getData();
	}

	private MainQuote mainQuotehandler(ApplyInsureRequest request, MainQuote main) throws Exception {
		int flag = 0;
		int lastFlag = 0;
		String isBICI = "";
		if (request.getBusStartTime() != null) {
			main.setStartDateBI(DateUtils.dateToString(request.getBusStartTime(), "yyyy-MM-dd"));
			main.setEndDateBI(
					DateUtils.dateToString(BaseUtil.getInsureEndDate(request.getBusStartTime()), "yyyy-MM-dd"));
			isBICI += "1";
			flag += 1;
		} else {
			main.setStartDateBI(DateUtils.dateToString(request.getForceStartTime(), "yyyy-MM-dd"));
			main.setEndDateBI(
					DateUtils.dateToString(BaseUtil.getInsureEndDate(request.getForceStartTime()), "yyyy-MM-dd"));
			isBICI += "0";
		}
		if (request.getForceStartTime() != null) {
			main.setStartDateCI(DateUtils.dateToString(request.getForceStartTime(), "yyyy-MM-dd"));
			main.setEndDateCI(
					DateUtils.dateToString(BaseUtil.getInsureEndDate(request.getForceStartTime()), "yyyy-MM-dd"));
			main.setChooseFlagCI(1);
			isBICI += "1";
			flag += 2;
		} else {
			main.setStartDateBI(DateUtils.dateToString(request.getBusStartTime(), "yyyy-MM-dd"));
			main.setEndDateBI(
					DateUtils.dateToString(BaseUtil.getInsureEndDate(request.getBusStartTime()), "yyyy-MM-dd"));
			isBICI += "0";
			main.setChooseFlagCI(0);
		}
		main.setIsBICI(isBICI);
		RenewalRequest renewalRequest = new RenewalRequest();
		renewalRequest.setLicenseNo(request.getUserVehicleInfo().getCarNum());
		renewalRequest.setLicenseType("02");
		RenewalPO isRenewal = renewalService.isRenewal(renewalRequest);
		if ("2".equals(isRenewal.getRenewalFlag())) {
			if (StringUtils.isNotBlank(isRenewal.getBiNo())) {
				lastFlag += 1;
			}
			if (StringUtils.isNotBlank(isRenewal.getCiNo())) {
				lastFlag += 2;
			}
			main.setEditType(MainQuote.RENEWAL_TYPE);
			main.setRenewalVehicle(isRenewal.getVehiclePO());
		} else {
			main.setEditType(MainQuote.NEW_TYPE);
		}
		main.setRenewalFlag(String.valueOf(lastFlag) + String.valueOf(flag));
		main.setRenewalPolicyNo(
				StringUtils.isNotBlank(isRenewal.getBiNo()) ? isRenewal.getBiNo() : isRenewal.getCiNo());
		main.setRandomProposalNo(getRandomProposalNo(main.getEditType()));
		BeanCopier.create(RbSysConfig.class, MainQuote.class, false).copy(rbSysConfig, main, null);
		return main;
	}

	private VehicleQuote vehicleQuotehandler(ApplyInsureRequest request, VehicleQuote vehicle,MainQuote main) throws Exception {
		UserVehicleInfo uVehicle = request.getUserVehicleInfo();
		VehicleInfo mVehicle = request.getVehicleInfo();
		vehicle.setLicenseNo(uVehicle.getCarNum());
		vehicle.setEngineNo(uVehicle.getEngineNo());
		vehicle.setVinNo(uVehicle.getVin());
		vehicle.setFrameNo(uVehicle.getVin());
		vehicle.setEnrollDate(DateUtils.dateToString(uVehicle.getFirstRegisterDate(), "yyyy-MM-dd"));
		
		vehicle.setModelCode(mVehicle.getModelCode());
		vehicle.setBrandName(mVehicle.getModelName());
		VehicleModelRequest vmRequest = new VehicleModelRequest();
		vmRequest.setModelCode(mVehicle.getModelCode());
		if (uVehicle.getTransferDate() != null) {
			vehicle.setTransferVehicleFlag(1);
			vehicle.setTransferDate(DateUtils.dateToString(uVehicle.getTransferDate(), "yyyy-MM-dd"));
		}
		List<VehicleModelPO> vms = vehicleService.getModelInfo(vmRequest);
		if (vms != null && !vms.isEmpty()) {
			VehicleModelPO vm = vms.get(0);
			
			vehicle.setPurchasePrice(vm.getPriceT());
			/**
			 * 注意转换 车辆信息定义为01--国产 02--进口 03--合资 车型查询定义为 1--国产 2--合资 3--进口
			 */
			if ("2".equals(vm.getVehicleType())) {
				vehicle.setCountryNature("03");
			} else if ("3".equals(vm.getVehicleType())) {
				vehicle.setCountryNature("02");
			} else {
				vehicle.setCountryNature("01");
			}
			vehicle.setSeatCount(mVehicle.getSeat());
			vehicle.setSeatCountTrue(vm.getVehicleSeat());
			if(mVehicle.getActualPrice()!=null) {
				vehicle.setActualValue(mVehicle.getActualPrice().doubleValue());
			}else {
				vehicle.setActualValue(BaseUtil.discount(request.getBusStartTime()!=null?request.getBusStartTime():request.getForceStartTime(), uVehicle.getFirstRegisterDate(),
						vm.getPriceT(), 2,
						mVehicle.getSeat()));
			}
			vehicle.setTonCount(StringUtils.isNotBlank(vm.getVehicleTonnage())
					? Double.valueOf(vm.getVehicleTonnage()).doubleValue() * 1000
					: 0d);
			vehicle.setExhaustScale(vm.getVehicleExhaust());
			vehicle.setCarLotEquQuality(
					vm.getVehicleQuality() != null ? vm.getVehicleQuality().doubleValue() * 1000 : null);
			vehicle.setModelCodeAlias(vm.getVehicleAlias());
			vehicle.setVehiclePricer(vm.getPriceTr());
			vehicle.setCarKindCode(vm.getVehicleClassPicc());
			vehicle.setUseYears(BaseUtil.carUseYears(
					request.getBusStartTime() != null ? request.getBusStartTime() : request.getForceStartTime(),
					uVehicle.getFirstRegisterDate()));
			
			if(request.getUserVehicleInfo().getTransferDate()==null &&  main!=null && main.getRenewalVehicle()!=null) {
				vehicle.setUseNatureCode(main.getRenewalVehicle().getUseNatureCode());
				vehicle.setClauseType(main.getRenewalVehicle().getClauseType());
				vehicle.setCarKindCode(main.getRenewalVehicle().getCarKindCode());
				vehicle.setLicenseType(main.getRenewalVehicle().getLicenseType());
				vehicle.setLicenseColorCode(main.getRenewalVehicle().getLicenseColorCode());
			}
			if(!"211".equals(vehicle.getUseNatureCode()) || !"F42".equals(vehicle.getClauseType()) ) {
				if(request.getUserVehicleInfo().getTransferDate()==null) {
					throw new BizException("车辆不属于家庭自用性质，不报价！");
				}
			}
			if(vehicle.getExhaustScale()==null || vehicle.getExhaustScale().compareTo(BigDecimal.ZERO)<=0) {
				vehicle.setEnergyType("1");
			}
		} else {
			throw new BizException("查询车型失败！");
		}
		return vehicle;
	}

	private PrivyPO privyQuotehandler(ApplyInsureRequest request, PrivyPO privy) throws Exception {
		UserInfo owner = request.getOwner();
		owner.setIdNo(owner.getIdNo().trim());
		UserInfo toubao = request.getToubao();
		toubao.setIdNo(toubao.getIdNo().trim());
		UserInfo beibao = request.getBeibao();
		beibao.setIdNo(beibao.getIdNo().trim());
		List<PrivyItemPO> items = Lists.newArrayList();
		int flag = 1;
		if (toubao == null || toubao.getIdNo().equals(owner.getIdNo())
				) {
			flag += 100;
		}
		if (beibao == null ||  beibao.getIdNo().equals(owner.getIdNo())
				) {
			flag += 10;
		}
		int index = 0;
		PrivyItemPO ownerPrivy = initPrivy(owner);
		if(ownerPrivy==null) {
			throw new BizException("关系人添加异常，请联系客服。");
		}
		if(!owner.getName().equals(ownerPrivy.getInsuredName())) privy.setPrivyStatus("invalid");
		
		ownerPrivy.setIndex(index++);
		ownerPrivy.setAge(owner.getAge() != null ? owner.getAge().toString()
				: owner.getBirthday() != null ? String.valueOf(BaseUtil.getAge(owner.getBirthday())) : null);
		ownerPrivy.setSerialNo(index);
		ownerPrivy.setInsuredType("1");
		ownerPrivy
				.setInsuredFlag(String.format("%03d", flag) + String.format("%026d", 0) + (flag >= 100 ? "A" : "0"));
		items.add(ownerPrivy);
		if (flag < 100) {
			if(toubao.getUserType()!=null && toubao.getUserType()==2) {
				PrivyItemPO toubaoPrivy = initGroup(toubao,request.getInvoiceInfo());
				if(!toubao.getName().equals(toubaoPrivy.getInsuredName())) privy.setPrivyStatus("invalid");
				toubaoPrivy.setIndex(index++);
				toubaoPrivy.setInsuredFlag("1"+(toubao.getIdNo().equals(beibao.getIdNo())?"1":"0")+String.format("%027d", 0)+"A");
				toubaoPrivy.setSerialNo(index);
				toubaoPrivy.setInsuredType("2");
				items.add(toubaoPrivy);
			}else {
				PrivyItemPO toubaoPrivy = initPrivy(toubao);
				if(!toubao.getName().equals(toubaoPrivy.getInsuredName())) privy.setPrivyStatus("invalid");
				toubaoPrivy.setIndex(index++);
				toubaoPrivy.setInsuredFlag("1"+(toubao.getIdNo().equals(beibao.getIdNo())?"1":"0")+String.format("%027d", 0)+"A");
				toubaoPrivy.setSerialNo(index);
				toubaoPrivy.setInsuredType("1");
				items.add(toubaoPrivy);
			}
		}
		if ((flag % 100) < 10 && !toubao.getIdNo().equals(beibao.getIdNo())) {
			PrivyItemPO beibaoPrivy = initPrivy(beibao);
			if(!beibao.getName().equals(beibaoPrivy.getInsuredName())) privy.setPrivyStatus("invalid");
			beibaoPrivy.setIndex(index++);
			beibaoPrivy.setInsuredFlag("01"+String.format("%028d", 0));
			beibaoPrivy.setSerialNo(index);
			beibaoPrivy.setInsuredType("1");
			items.add(beibaoPrivy);
		}

		privy.setItems(items);
		return privy;
	}
	private PrivyItemPO initGroup(UserInfo info,InvoiceInfo invoice) throws Exception {
		PrivyRequest _request = new PrivyRequest();
		_request.setUnifiedSocialCreditCode(info.getIdNo());
		_request.set_insuredName(info.getName());
		GoupItemPO po = privyService.getGroupInfo(_request);
		GroupEditRequest request = new GroupEditRequest();
		request.setBusinessSort("04".equals(info.getCustomerType())?"300":"900");
		request.setCustomerCName(info.getName());
		request.setUnifiedSocialCreditCode(info.getIdNo());
		request.setEmail(info.getEmail());
		PersonAddress address = new PersonAddress();
		address.setAddresscname(info.getAddress());
		request.setAddresses(Lists.newArrayList(address));
		PersonContact contact = new PersonContact();
		 contact.setPhoneType("1");
		 contact.setPhoneNumber(info.getMobile());
		request.setContacts(Lists.newArrayList(contact));
		if(invoice!=null && "02".equals(invoice.getInvoicePrintType())) {
			GroupTax tax = new GroupTax();
			tax.setAccount(invoice.getBankAccount());
			tax.setTaxType("1");
			tax.setAddress(invoice.getAddress());
			tax.setBankView(invoice.getDepositBank());
			tax.setBank(invoice.getDepositBank());
			tax.setIdNo(invoice.getTaxpayerCertificateNo());
			tax.setPhone(invoice.getPhone());
			request.setTax(tax);
		}
		if (po == null) {
			// 使用随机手机号码
			Model<String> check = privyService.checkRepeat(null, info.getMobile());
			if (check != null && StringUtils.isNotBlank(check.getMsg())) {
				if (!rbSysConfig.isRandomMobile())
					throw new BizException(check.getMsg());
				contact.setPhoneNumber(BaseUtil.getRandomMobile());
			}
			String code = privyService.addGroup(request);
			if (StringUtils.isNotBlank(code)) {
				_request.setUnifiedSocialCreditCode(null);
				_request.set_insuredCode(code);
				po = privyService.getGroupInfo(_request);
			} else {
				throw new BizException("增加团体关系人失败。");
			}
		}else if (StringUtils.isBlank(po.getInsuredAddress())
				|| po.getInsuredAddress().length()<12
				|| (StringUtils.isBlank(po.getMobileNoYG()) && StringUtils.isBlank(po.getPhoneNumber()))
				) {
			// 使用随机手机号码
			Model<String> check = privyService.checkRepeat(po.getInsuredCode(), info.getMobile());
			if (check != null && StringUtils.isNotBlank(check.getMsg())) {
				if (!rbSysConfig.isRandomMobile())
					throw new BizException(check.getMsg());
				contact.setPhoneNumber(BaseUtil.getRandomMobile());
			}
			request.setCustomerCode(po.getInsuredCode());
			if(!po.getInsuredName().equals(info.getName())) request.setCustomerCName(info.getName());
			String code = privyService.updGroup(request);
			if (StringUtils.isNotBlank(code)) {
				_request.set_identifyNumber(null);
				_request.set_identifyType(null);
				_request.set_insuredCode(code);
				return privyService.getPrivyInfo(_request);
			} else {
				throw new BizException("更新团体关系人失败。");
			}
		}
//		else if("2".equals(po.getAuditStatus())){
//			throw new BizException("机构信息未审批通过，不能报价,请联系客服。");
//		}
		PrivyItemPO privy = new PrivyItemPO();
		BeanCopier.create(GoupItemPO.class, PrivyItemPO.class, false).copy(po, privy, null);
		return privy;
	}
	
	private PrivyItemPO initPrivy(UserInfo info) throws Exception {
		PrivyRequest _request = new PrivyRequest();
		_request.set_identifyNumber(info.getIdNo());
		_request.set_identifyType("02".equals(info.getCustomerType()) || "2".equals(info.getCustomerType())? "03" : "01");
		_request.set_insuredName(info.getName());
		PrivyItemPO po = privyService.getPrivyInfo(_request);
		if (po == null) {
			PrivyEditRequest addRequest = new PrivyEditRequest();
			addRequest.setIdentifyNumber(info.getIdNo());
			addRequest.setIdentifyType("02".equals(info.getCustomerType()) || "2".equals(info.getCustomerType())? "03" : "01");
			addRequest.setType(info.getUserType().toString());
			addRequest.setCustomerCName(info.getName());
			addRequest.setGender(info.getSex());
			addRequest.setPhoneNumber(info.getMobile());
			addRequest.setBirthDate(DateUtils.dateToString(info.getBirthday(), "yyyy-MM-dd"));
			addRequest.setAddresscname(info.getAddress());
			Model<String> check = privyService.checkRepeat(null, info.getMobile());
			if (check!=null && StringUtils.isNotBlank(check.getMsg())) {
				if (!rbSysConfig.isRandomMobile())
					throw new BizException(check.getMsg());
				addRequest.setPhoneNumber(BaseUtil.getRandomMobile());
			}
			String code = privyService.addCustomer(addRequest);
			if (StringUtils.isNotBlank(code)) {
				_request.set_identifyNumber(null);
				_request.set_identifyType(null);
				_request.set_insuredCode(code);
				return privyService.getPrivyInfo(_request);
			} else {
				return null;
			}
		} else if (StringUtils.isBlank(po.getInsuredAddress())
				|| po.getInsuredAddress().length()<12
				|| (StringUtils.isBlank(po.getMobileNoYG()) && StringUtils.isBlank(po.getPhoneNumber()))
				|| (StringUtils.isNotBlank(po.getMobileNoYG()) && (po.getMobileNoYG().length()!=11 || !StringUtils.isNumeric(po.getMobileNoYG())))
				|| (StringUtils.isNotBlank(po.getPhoneNumber()) && ((po.getPhoneNumber().length()>=7 && po.getPhoneNumber().length()<=12) || !StringUtils.isNumeric(po.getPhoneNumber())))
				) {
			PrivyEditRequest addRequest = new PrivyEditRequest();
			addRequest.setCustomerCode(po.getInsuredCode());
			if(!po.getInsuredName().equals(info.getName())) addRequest.setCustomerCName(info.getName());
			addRequest.setGender(info.getSex());
			addRequest.setPhoneNumber(info.getMobile());
			// 使用随机手机号码
			Model<String> check = privyService.checkRepeat(po.getInsuredCode(), info.getMobile());
			if (check!=null && StringUtils.isNotBlank(check.getMsg())) {
				if (!rbSysConfig.isRandomMobile())
					throw new BizException(check.getMsg());
				addRequest.setPhoneNumber(BaseUtil.getRandomMobile());
			}
			addRequest.setBirthDate(DateUtils.dateToString(info.getBirthday(), "yyyy-MM-dd"));
			addRequest.setAddresscname(info.getAddress());
			String code = privyService.updateCustomer(addRequest);
			if (StringUtils.isNotBlank(code)) {
				_request.set_identifyNumber(null);
				_request.set_identifyType(null);
				_request.set_insuredCode(code);
				return privyService.getPrivyInfo(_request);
			} else {
				return null;
			}
		} else {
			return po;
		}
	}

	private static Map<String, KindConfig> kindItem = new HashMap<String, KindConfig>() {
		private static final long serialVersionUID = -7664246714261312333L;
		{
			put("JQ", new KindConfig("机动车交通事故强制责任保险", "050100", "050001", null, null, 30));
			put("CCS", new KindConfig("车船税", null, null, null, null, 31));
			put("CheSun", new KindConfig("机动车损失保险", "050202", "050051", "Y11Y000", "050930", 3));
			put("BuJiMianCheSun", new KindConfig("不计免赔险（车损险）", "050930", "050066", "N33N000", null, 4));
			put("SanZhe", new KindConfig("第三者责任保险", "050602", "050052", "Y21Y000", "050931", 5));
			put("BuJiMianSanZhe", new KindConfig("不计免赔险（三者险）", "050931", "050066", "N33N000", null, 6));
			put("SiJi", new KindConfig("车上人员责任险（司机）", "050711", "050053", "Y21Y00", "050933", 7));
			put("BuJiMianSiJi", new KindConfig("不计免赔险（车上人员（司机））", "050933", "050066", "N33N000", null, 8));
			put("ChengKe", new KindConfig("车上人员责任险（乘客）", "050712", "050053", "Y21Y000", "050934", 9));
			put("BuJiMianChengKe", new KindConfig("不计免赔险（车上人员（乘客））", "050934", "050066", "N33N000", null, 10));
			put("DaoQiang", new KindConfig("盗抢", "050501", "050054", "N11Y000", "050932", 11));
			put("BuJiMianDaoQiang", new KindConfig("不计免赔险（盗抢险）", "050932", "050066", "N33N000", null, 12));
			put("HuaHen", new KindConfig("车身划痕损失险", "050211", "050059", "N12Y000", "050937", 13));
			put("BuJiMianHuaHen", new KindConfig("不计免赔险（车身划痕损失险）", "050937", "050066", "N33N000", null, 14));
			put("BoLi", new KindConfig("玻璃单独破碎险", "050232", "050056", "N32N000", null, 15));
			put("ZiRan", new KindConfig("自燃损失险", "050311", "050057", "N12Y000", "050935", 16));
			put("BuJiMianZiRan", new KindConfig("不计免赔险（自燃损失险）", "050935", "050066", "N33N000", null, 17));
			put("SheShui", new KindConfig("发动机涉水损失险", "050461", "050066", "N33N000", null, 18));
			put("BuJiMianSheShui", new KindConfig("不计免赔险（发动机涉水损失险）", "050938", "050066", "N33N000", null, 19));
			put("HcXiuLiChang", new KindConfig("指定修理厂险", "050253", "050065", "N32N000", null, 20));
			put("HcSanFangTeYue", new KindConfig("机动车损失保险无法找到第三方特约险", "050451", "050064", "N32N000", null, 21));
		}
	};

	private BIPO biQuotehandler(ApplyInsureRequest request, MainQuote main) throws Exception {
		BIPO bi = new BIPO();
		if (request.getBusStartTime() == null)
			return bi;
		Quote quote = request.getQuote();
		List<KindPO> kinds = Lists.newArrayList();
		boolean isRenewal = StringUtils.isNotBlank(main.getRenewalPolicyNo());
		int index =0;
		if (quote.getDamage() != null) {
			kinds.add(initFlag(kindHandler(quote.getDamage(), "CheSun", null,index++), isRenewal, true,
					quote.getNoRejectDamage() != null));
		}
		if (quote.getRobbery() != null) {
			kinds.add(initFlag(kindHandler(quote.getRobbery(), "DaoQiang", null,index++), isRenewal, true,
					quote.getNoRejectRobbery() != null));
		}
		if (quote.getThirdPartyAmount() != null) {
			kinds.add(initFlag(kindHandler(quote.getThirdPartyAmount(), "SanZhe", null,index++), isRenewal, true,
					quote.getNoRejectThirdParty() != null));
		}
		if (quote.getDriverAmount() != null) {
			kinds.add(initFlag(kindHandler(quote.getDriverAmount(), "SiJi", null,index++), isRenewal, true,
					quote.getNoRejectDriver() != null));
		}
		if (quote.getPassengerAmount() != null) {
			kinds.add(
					initFlag(kindHandler(quote.getPassengerAmount(), "ChengKe", request.getVehicleInfo().getSeat() - 1,index++),
							isRenewal, true, quote.getNoRejectPassenger() != null));
		}
		if (quote.getScratch() != null) {
			kinds.add(initFlag(kindHandler(quote.getScratch(), "HuaHen", null,index++), isRenewal, false,
					quote.getNoRejectScratch() != null));
		}
		// 玻璃0--国产 1--进口
		if (quote.getGlass() != null) {
			kinds.add(initFlag(kindHandler(quote.getGlass().intValue() == 0 ? 10d : 20d, "BoLi", null,index++), isRenewal,
					false, false));
		}
		if (quote.getDesignatedService() != null) {
			kinds.add(
					initFlag(kindHandler(quote.getDesignatedService(), "HcXiuLiChang", null,index++), isRenewal, false, false));
		}
		if (quote.getFire() != null) {
			kinds.add(initFlag(kindHandler(quote.getFire(), "ZiRan", null,index++), isRenewal, false,
					quote.getNoRejectFire() != null));
		}
		if (quote.getEngine() != null) {
			kinds.add(initFlag(kindHandler(quote.getEngine(), "SheShui", null,index++), isRenewal, false,
					quote.getNoRejectEngine() != null));
		}
		if (quote.getHcSanFangTeYue() != null) {
			kinds.add(
					initFlag(kindHandler(quote.getHcSanFangTeYue(), "HcSanFangTeYue", null,index++), isRenewal, false, false));
		}
		if (quote.getNoRejectDamage() != null) {
			kinds.add(
					initFlag(kindHandler(quote.getNoRejectDamage(), "BuJiMianCheSun", null,index++), isRenewal, false, false));
		}
		if (quote.getNoRejectThirdParty() != null) {
			kinds.add(initFlag(kindHandler(quote.getNoRejectThirdParty(), "BuJiMianSanZhe", null,index++), isRenewal, false,
					false));
		}
		if (quote.getNoRejectRobbery() != null) {
			kinds.add(initFlag(kindHandler(quote.getNoRejectRobbery(), "BuJiMianDaoQiang", null,index++), isRenewal, false,
					false));
		}
		if (quote.getNoRejectDriver() != null) {
			kinds.add(initFlag(kindHandler(quote.getNoRejectDriver(), "BuJiMianSiJi", null,index++), isRenewal, false, false));
		}
		if (quote.getNoRejectPassenger() != null) {
			kinds.add(initFlag(kindHandler(quote.getNoRejectPassenger(), "BuJiMianChengKe", null,index++), isRenewal, false,
					false));
		}
		if (quote.getNoRejectScratch() != null) {
			kinds.add(
					initFlag(kindHandler(quote.getNoRejectScratch(), "BuJiMianHuaHen", null,index++), isRenewal, false, false));
		}
		if (quote.getNoRejectFire() != null) {
			kinds.add(initFlag(kindHandler(quote.getNoRejectFire(), "BuJiMianZiRan", null,index++), isRenewal, false, false));
		}
		if (quote.getNoRejectEngine() != null) {
			kinds.add(
					initFlag(kindHandler(quote.getNoRejectEngine(), "BuJiMianSheShui", null,index++), isRenewal, false, false));
		}
		bi.setKinds(kinds);
		return bi;
	}

	/**
	 * 初始化险种标志 isRenewal 是否续保 isMain 是否主险 isNoReject 是否不计免
	 * 
	 * @param isRenewal
	 */
	private KindPO initFlag(KindPO po, boolean isRenewal, boolean isMain, boolean isNoReject) {
		po.setFlag(String.join("", " ", isMain ? "1" : "2", "00", isNoReject ? "1" : "0", "000", "  "));
		if (isNoReject)
			po.setSpecialFlag("on");
		return po;
	}

	/**
	 * 玻璃险10国产 20进口
	 * 
	 * @param flag
	 * @param kindCode
	 */
	private KindPO kindHandler(Double flag, String kindCode, Integer quantity,int index) {
		if (flag == null)
			return null;
		KindPO kind = new KindPO();
		kind.setIndex(index);
		KindConfig config = kindItem.get(kindCode);
		kind.setChooseFlag("on");
		kind.setKindCode(config.getKindCode());
		kind.setKindName(config.getKindName());
		kind.setClauseCode(config.getClauseCode());
		kind.setRelateSpecial(config.getRelateSpecial());
		kind.setCalculateFlag(config.getCalculateFlag());
		// if(isNoReject) kind.setSpecialFlag("on");
		if ("HcXiuLiChang".equals(kindCode)) {
			kind.setRate(15d);
		}else if("SanZhe".equals(kindCode)) {
			if(flag.compareTo(1000000d)>0) {
				kind.setAmountView(String.valueOf(flag/10000));
				kind.setSelectOption("100-1000");
			}else {
				kind.setAmountView(String.valueOf(flag/10000));
				kind.setSelectOption(String.valueOf(flag/10000));
			}
		}
		if (flag.intValue() > 1) {
			if ("BoLi".equals(kindCode)) {
				kind.setModeCode(String.valueOf(flag.intValue()));
			} else {
				kind.setAmount(flag);
			}
			if (quantity != null) {
				kind.setAmount(flag * quantity);
				kind.setUnitAmount(flag);
				kind.setQuantity(quantity);
			}
		}
		return kind;
	}

	private CIPO ciQuotehandler(ApplyInsureRequest request, PrivyPO privy,MainQuote main) throws Exception {
		CIPO ci = new CIPO();
		if (request.getForceStartTime() == null) {
			ci.setFamilyNo("0");
			ci.setcIBPFlag("0");
			return ci;
		}
		ci.setFamilyNo("1");
		ci.setcIBPFlag("1");
		ShipTaxPO tax = new ShipTaxPO();
		tax.setTaxPayerIdentNo(request.getBeibao().getIdNo());
		tax.setTaxPayerNumber(request.getBeibao().getIdNo());
		tax.setTaxType("1");
		tax.setCalculateMode("C1");
		tax.setTaxPayerNature("3");
		tax.setTaxPayerName(request.getBeibao().getName());
		privy.getItems().forEach(p -> {
			if (("1").equals(p.getInsuredFlag().substring(1, 2)))
				tax.setTaxPayerCode(p.getInsuredCode());
		});
		tax.setPrePayTaxYear(String.valueOf(LocalDate.now().getYear() - 1));
		TaxRequest _request = new TaxRequest();
		_request.setComCode(this.rbSysConfig.getComCode());
		_request.setEnrollDate(
				DateUtils.dateToString(request.getUserVehicleInfo().getFirstRegisterDate(), "yyyy-MM-dd"));
		_request.setModelCode(request.getVehicleInfo().getModelCode());
		_request.setLicenseType("02");
		tax.setTaxRegistryNumber("91440101712412249C");
		
		TaxQueryPO taxPO = kindService.queryTax(_request);
		if (taxPO != null) {
			if (taxPO.getTaxType() != null) {
				tax.setTaxType(taxPO.getTaxType().toString());
			}
			tax.setTaxAbateType(taxPO.getTaxAbateType());
			tax.setTaxAbateReason(taxPO.getTaxAbateReason());
			tax.setTaxAbateRate(taxPO.getTaxAbateRate());
			// BeanCopier.create(TaxQueryPO.class, ShipTaxPO.class, false).copy(taxPO, tax,
			// null);
			if ("02".equals(taxPO.getTaxAbateReason()) || "04".equals(taxPO.getTaxAbateReason())) {
				tax.setDutyPaidProofNo_1("244999");
			} else if ("03".equals(taxPO.getTaxAbateReason())) { // 拖拉机
				tax.setDutyPaidProofNo_1("244111");
			} else if ("03".equals(taxPO.getTaxAbateReason()) || "09".equals(taxPO.getTaxAbateReason())
					|| "10".equals(taxPO.getTaxAbateReason())) {
				tax.setDutyPaidProofNo_1("244555");
			} else if ("08".equals(taxPO.getTaxAbateReason()) || "07".equals(taxPO.getTaxAbateReason())
					|| "06".equals(taxPO.getTaxAbateReason())) { // 商品车
				tax.setDutyPaidProofNo_1("244888");
			} else if ("11".equals(taxPO.getTaxAbateReason())) { // 商品车
				tax.setDutyPaidProofNo_1("244777");
			} else if ("12".equals(taxPO.getTaxAbateReason())) { // 农村居民拥有并主要在农村地区使用的低速载货汽车
				tax.setDutyPaidProofNo_1("244444");
			} else if ("13".equals(taxPO.getTaxAbateReason())) { // 农村居民拥有并主要在农村地区使用的三轮汽车
				tax.setDutyPaidProofNo_1("244333");
			} else if ("14".equals(taxPO.getTaxAbateReason())) { // 农村居民拥有并主要在农村地区使用的摩托车
				tax.setDutyPaidProofNo_1("244222");
			}
			tax.setDutyPaidProofNo(tax.getDutyPaidProofNo_1());
		}
		tax.setTaxComCode(rbSysConfig.getTaxComCode());
		tax.setTaxComName(rbSysConfig.getTaxComName());
		
		ci.setTax(tax);
		return ci;
	}

	public String test(String url, String templateName) {
		try {
			String strBody = compiler.compile(mustacheTemplateLoader.getTemplate(templateName)).execute("test");
			ResponseModel<String> privyResponse = okHttpClientService.postHtml(url, strBody, String.class);
			if (privyResponse.isSuccessful() && privyResponse.getBody() != null) {
				return privyResponse.getBody();
			}
		} catch (Exception e) {
			LOGGER.error("QuoteServiceImpl quote fail.", e);
		}
		return null;
	}
}
